public class TestUDP {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
DatagramSocket send = new DatagramSocket();
Send s = new Send(send);
DatagramSocket rece = new DatagramSocket(10001);
Receive r = new Receive(rece);
new Thread(s).start();
new Thread(r).start();
}
}
public class Send implements Runnable {
private DatagramSocket ds;
Send(DatagramSocket ds) {
this.ds = ds;
}
@Override
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
try {
while ((line = br.readLine()) != null) {
byte[] bys = line.getBytes();
InetAddress in = InetAddress.getLocalHost();
DatagramPacket dp = new DatagramPacket(bys, bys.length, in,
10001);
ds.send(dp);
if(line.equalsIgnoreCase("over"))
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Receive implements Runnable {
private DatagramSocket ds;
Receive(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 data=new String(dp.getData(),0,dp.getLength());
System.out.println(dp.getAddress().getHostAddress()+":"+data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
UDP多线程操作
最新推荐文章于 2024-07-14 14:51:30 发布