Java基础知识强化之网络编程笔记05:UDP之多线程实现聊天室案例

1. 通过多线程改进刚才的聊天程序,这样我就可以实现在一个窗口发送和接收数据了

2.  代码示例:

(1)SendThread.java,如下:

 package com.himi.udpDemo2;

 import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress; public class SendThread implements Runnable { private DatagramSocket ds; public SendThread(DatagramSocket ds) {
this.ds = ds;
} public void run() {
try {
// 封装键盘录入数据
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
String line = null;
while ((line = br.readLine()) != null) {
if ("886".equals(line)) {
break;
} // 创建数据并打包
byte[] bys = line.getBytes();
// DatagramPacket dp = new DatagramPacket(bys, bys.length,
// InetAddress.getByName("192.168.12.92"), 12345);
DatagramPacket dp = new DatagramPacket(bys, bys.length,
InetAddress.getByName("49.123.72.145"), 12306); // 发送数据
ds.send(dp);
} // 释放资源
ds.close();
} catch (IOException e) {
e.printStackTrace();
}
} }

(2)ReceiveThread.java,如下:

 package com.himi.udpDemo2;

 import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket; public class ReceiveThread implements Runnable {
private DatagramSocket ds; public ReceiveThread(DatagramSocket ds) {
this.ds = ds;
} public void run() {
try {
while (true) {
// 创建一个包裹
byte[] bys = new byte[1024];
DatagramPacket dp = new DatagramPacket(bys, bys.length); // 接收数据
ds.receive(dp); // 解析数据
String ip = dp.getAddress().getHostAddress();
String s = new String(dp.getData(), 0, dp.getLength());
System.out.println("from " + ip + " data is : " + s);
}
} catch (IOException e) {
e.printStackTrace();
}
} }

(3)聊天室程序CharRoom.java,调用上面两个线程工具类,代码如下:

 package com.himi.udpDemo2;

 import java.io.IOException;
import java.net.DatagramSocket; /*
* 通过多线程改进刚才的聊天程序,这样我就可以实现在一个窗口发送和接收数据了
*/
public class ChatRoom {
public static void main(String[] args) throws IOException {
DatagramSocket dsSend = new DatagramSocket();
DatagramSocket dsReceive = new DatagramSocket(12306); SendThread st = new SendThread(dsSend);
ReceiveThread rt = new ReceiveThread(dsReceive); Thread t1 = new Thread(st);
Thread t2 = new Thread(rt); t1.start();
t2.start();
}
}

运行效果如下:

Java基础知识强化之网络编程笔记05:UDP之多线程实现聊天室案例

上一篇:MYSQL 分组合并函数


下一篇:【Java】Socket+多线程实现控制台聊天室