UDP传输:(四)通过多线程改进,在一个窗口中同时接收又发送
import java.io.IOException;
import java.net.DatagramSocket;
/*
* 通过多线程改进刚才的聊天程序,这样我就可以实现在一个窗口发送和接收数据了
*/
public class ChatRoom {
publicstatic void main(String[] args) throws IOException {
DatagramSocketdsSend = new DatagramSocket();
DatagramSocketdsReceive = new DatagramSocket(12306);
SendThreadst = new SendThread(dsSend);
ReceiveThreadrt = new ReceiveThread(dsReceive);
Threadt1 = new Thread(st);
Threadt2 = new Thread(rt);
t1.start();
t2.start();
}
}
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{
privateDatagramSocket ds;
publicSendThread(DatagramSocket ds) {
this.ds= ds;
}
@Override
publicvoid run() {
try{
//封装键盘录入数据
BufferedReaderbr = new BufferedReader(new InputStreamReader(
System.in));
Stringline = 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);
DatagramPacketdp = new DatagramPacket(bys, bys.length,
InetAddress.getByName("219.216.80.19"),12306);
//发送数据
ds.send(dp);
}
//释放资源
ds.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class ReceiveThread implementsRunnable {
privateDatagramSocket ds;
publicReceiveThread(DatagramSocket ds) {
this.ds= ds;
}
@Override
publicvoid run() {
try{
while(true) {
//创建一个包裹
byte[]bys = new byte[1024];
DatagramPacketdp = new DatagramPacket(bys, bys.length);
//接收数据
ds.receive(dp);
//解析数据
Stringip = dp.getAddress().getHostAddress();
Strings = new String(dp.getData(), 0, dp.getLength());
System.out.println("from" + ip + " data is : " + s);
}
}catch (IOException e) {
e.printStackTrace();
}
}
}