黑马程序员技术交流社区
标题:
udp传输问题。
[打印本页]
作者:
汪洋大海
时间:
2013-11-29 02:44
标题:
udp传输问题。
各位同学们,你们好,我想问一下,一个程序可以设置多个接收端口吗?如果可以的设置多个端口,如何和多线程配合使用呢?
如果不可以,是为什么呢?
最好可以配上简单的代码,谢谢了哟。
作者:
冯晓骏
时间:
2013-11-29 04:12
服务器代码
public class UdpServer {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
//开启一个线程,监听端口10000的数据包
Executors.newSingleThreadExecutor().execute(
new Runnable(){
public void run(){
try {
DatagramSocket ds = new DatagramSocket(10000);
byte[] buf = new byte[1024];
int length = 0;
DatagramPacket dp = new DatagramPacket(buf, 1024);
while (true) {
ds.receive(dp);
System.out.println(dp.getAddress()+"::"+dp.getLength()+":"+new String(dp.getData(), 0, dp.getLength()));
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
});
//开启一个线程,监听端口10001的数据包
Executors.newSingleThreadExecutor().execute(
new Runnable(){
public void run(){
try {
DatagramSocket ds = new DatagramSocket(10001);
byte[] buf = new byte[1024];
int length = 0;
DatagramPacket dp = new DatagramPacket(buf, 1024);
while (true) {
ds.receive(dp);
System.out.println(dp.getAddress()+"::"+dp.getLength()+":"+new String(dp.getData(), 0, dp.getLength()));
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
});
}
}
复制代码
客户端代码
public class UdpClient {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//开启一个线程,向本机的10000端口发送数据包
Executors.newSingleThreadExecutor().execute(
new Runnable(){
public void run(){
try {
DatagramSocket ds = new DatagramSocket();
byte[] buf = "THIS IS NO.1".getBytes();
InetAddress ia = InetAddress.getLocalHost();
DatagramPacket dp = new DatagramPacket(buf, buf.length, ia, 10000);
while (true) {
ds.send(dp);
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
});
//开启一个线程,向本机的10001端口发送数据包
Executors.newSingleThreadExecutor().execute(
new Runnable(){
public void run(){
try {
DatagramSocket ds = new DatagramSocket();
byte[] buf = "this is No.2".getBytes();
InetAddress ia = InetAddress.getLocalHost();
DatagramPacket dp = new DatagramPacket(buf, buf.length, ia, 10001);
while (true) {
ds.send(dp);
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
});
}
}
复制代码
功能:客户端想服务端的不同端口发送请求
作者:
汪洋大海
时间:
2013-11-29 07:35
谢谢你了。原来是这样呀。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2