黑马程序员技术交流社区
标题:
【分享】UDP多线程操作
[打印本页]
作者:
暗影流光
时间:
2014-7-12 10:16
标题:
【分享】UDP多线程操作
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();
}
}
}
复制代码
作者:
jwx555
时间:
2014-7-12 13:12
一句注释都没有,懒得看了都
作者:
導ぷ仙″兲蕐
时间:
2014-7-12 13:21
额 ,提问结束??
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2