实现UDP的双向聊天室
作者:互联网
利用Sockket和多线程实现的UDP双向聊天室
发送端
public class UdpSend implements Runnable{
private DatagramSocket ds;
private BufferedReader br;
int toPort;
String toID;
UdpServer(int i,String s,int j) throws Exception{
this.toPort = j;
this.toID = s;
ds = new DatagramSocket(i);
br = new BufferedReader(new InputStreamReader(System.in));
}
@Override
public void run() {
while(true) {
String data;
try {
data = br.readLine();
byte[] temp = data.getBytes();
DatagramPacket pac = new DatagramPacket(temp,0,temp.length,
new InetSocketAddress(toID,toPort));
ds.send(pac);
if(data.equals("bye"))break;
} catch (Exception e) {
ds.close();
}
}
ds.close();
}
}
接收端
public class UdpClient implements Runnable{
private DatagramSocket ds;
int naPort;
UdpClient(int i) throws Exception{
this.naPort = i;
ds = new DatagramSocket(naPort);
}
@Override
public void run() {
while(true) {
byte[] data = new byte[1024*60];
DatagramPacket pac = new DatagramPacket(data,0,data.length);
try {
ds.receive(pac);//阻塞式接收
byte[] ndata = pac.getData();
String talk = new String(ndata,0,pac.getLength());
System.out.println(talk);
if(talk.equals("bye"))break;
} catch (Exception e) {
ds.close();
}
}
ds.close();
}
}
调用线程实现双向同时发送信息,双方都说了bye线程关闭。
是不是很简单
标签:UDP,String,int,聊天室,pac,双向,new,data,ds 来源: https://blog.csdn.net/Willy146/article/details/104609972