网络编程_多线程实现聊天室程序
原创
©著作权归作者所有:来自51CTO博客作者wx62dfdc6aea345的原创作品,请联系作者获取转载授权,否则将追究法律责任
package cn.itcast_05;
import java.io.IOException;
import java.net.DatagramSocket;
/*
* 通过多线程改进聊天室程序,这样就可以实现在一个窗口发送和接收数据了
*/
public class ChatRoom {
public static void main(String[] args) throws IOException {
// 发送端对象
DatagramSocket dsSed = new DatagramSocket();
// 接收端对象
DatagramSocket dsReceive = new DatagramSocket(12306);
// 发送端
SedThread st = new SedThread(dsSed);
// 接收端
ReceiveThread rt = new ReceiveThread(dsReceive);
Thread t1 = new Thread(st);
Thread t2 = new Thread(rt);
// 启动线程
t1.start();
t2.start();
}
}
package cn.itcast_05;
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;
}
@Override
public void run() {
// 创建接收数据包
byte[] bys = new byte[1024];
DatagramPacket dp = new DatagramPacket(bys, bys.length);
try {
while (true) {
// 接收数据
ds.receive(dp);
// 解析数据,并显示在控制台
String ip = dp.getAddress().getHostAddress();
String s = new String(dp.getData(), 0, dp.getLength());
System.out.println("form " + ip + " data is:" + s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package cn.itcast_05;
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 SedThread implements Runnable {
// 发送端Socket对象
private DatagramSocket ds;
public SedThread(DatagramSocket ds) {
this.ds = ds;
}
@Override
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.31.255"), 12306);
// 发送数据
ds.send(dp);
}
// 释放资源
ds.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}