利用多线程,实现网络聊天室
- 1:发送端的线程
* 2:接收端的线程
* 3:测试类
* 从上面两个来看,UDP编程时最好不要超过1472(针对以太网),如果要求不 高, 就算超过了1472了,
* 可以超过65507,即包总大小不要超过64k
import java.io.IOException;
import java.net.DatagramSocket;
public class Test {
public static void main(String[] args) throws IOException {
//1:创建发送端的实例
SendRunn sr = new SendRunn(new DatagramSocket());
//2:创建发送端的线程
Thread t1 = new Thread(sr);
//3:创建接收端的实例
ReceiveRunn rr = new ReceiveRunn(new DatagramSocket(10086));
//4:创建接受端的线程
Thread t2 = new Thread(rr);
//5:启动线程
t1.start();
t2.start();
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
/*
* 发送端线程
*/
public class SendRunn implements Runnable {
//声明发送端的套接字
private DatagramSocket ds;
public SendRunn(DatagramSocket ds) {
this.ds = ds;
}
@Override
public void run() {
try {
BufferedReader br = new BufferedReader(new FileReader("斗破苍穹.txt"));
char[] ch = new char[1024*1024];
int read = br.read(ch);
String info = new String(ch, 0,read);
//1数据
byte[] by = info.getBytes();
//1:创建数据包
DatagramPacket dp = new DatagramPacket(by, by.length, InetAddress.getByName("192.168.3.255"), 10086);
//2:发送数据宝
ds.send(dp);
} catch (IOException e) {
e.printStackTrace();
}
//关闭套集字
ds.close();
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;
public class ReceiveRunn implements Runnable {
private DatagramSocket ds;
public ReceiveRunn(DatagramSocket ds) {
super();
this.ds = ds;
}
@Override
public void run() {
while(true){
//1:创建空的数据包
byte[] by = new byte[1024*1024];
DatagramPacket dp = new DatagramPacket(by, by.length);
try {
//2:接受数据,并且把数据封装到数据包中
ds.receive(dp);
//3:拆封数据
byte[] data = dp.getData();
int length = dp.getLength();
InetAddress address = dp.getAddress();
String hostName = address.getHostName();
System.out.println(length);
System.out.println(hostName+" "+new Date().toLocaleString());
System.out.println(new String(by, 0, length));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}