本帖最后由 徐鑫 于 2012-4-23 13:03 编辑
以下代码可以直接进行编译,运行
import java.net.*;
import java.io.*;
class udpSend2{
public static void main(String args[]) throws Exception{
DatagramSocket ds = new DatagramSocket();
BufferedReader buffr = new BufferedReader(new InputStreamReader(System.in));
byte[] data = new byte[1024];
String line = null;
while((line = buffr.readLine())!= null){
if(line.equals("886"))break;
data = line.getBytes();
DatagramPacket dp = new DatagramPacket(data,data.length,InetAddress.getByName("192.168.1.3"),10024);
ds.send(dp);
}
ds.close();
}
}
class udpReceive2{
public static void main(String args[]) throws Exception{
while(true){
DatagramSocket ds = new DatagramSocket(10024);
byte[] bytes = new byte[1024];
DatagramPacket dp = new DatagramPacket(bytes,bytes.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
System.out.println(ip+"::"+data);
}
}
}
这是毕老师网络编程UDP协议通信的例子,代码在运行时,发送端发送第一个内容时,接收端接收到了但同时报了Address is using cannot bind....求高手指点
|
-
1.png
(18.35 KB, 下载次数: 46)
-
2.png
(45.8 KB, 下载次数: 66)
接收端
|