本帖最后由 张向辉 于 2013-1-22 20:15 编辑
发送端
/**
*
*/
package cn.soft;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* @author pc-fei
*
*/
public class UdpSendDemo {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
System.out.println("发送启动");
DatagramSocket ds=new DatagramSocket();
String str="我来了";
byte[] buf=str.getBytes();
DatagramPacket dp=new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.1.2"), 10000);
ds.send(dp);
ds.close();
}
}
接收端
/**
*
*/
package cn.soft;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
/**
* @author pc-fei
*
*/
public class UpdReceDemo {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
System.out.println("接收启动");
DatagramSocket datagramSocket=new DatagramSocket(10000);
byte[] buf=new byte[1024];
DatagramPacket datagramPacket=new DatagramPacket(buf, buf.length);
datagramSocket.receive(datagramPacket);
String ip=datagramPacket.getAddress().getHostAddress();
int port=datagramPacket.getPort();
String text=new String(datagramPacket.getData(),0,datagramPacket.getLength());
System.out.println(ip+":"+port+":"+text);
datagramSocket.close();
}
}
我这样写然后运行就报错,接收端显示异常
接收启动
Exception in thread "main" java.net.SocketException: Unrecognized Windows Sockets error: 0: Cannot bind
at java.net.PlainDatagramSocketImpl.bind0(Native Method)
at java.net.PlainDatagramSocketImpl.bind(PlainDatagramSocketImpl.java:82)
at java.net.DatagramSocket.bind(DatagramSocket.java:368)
at java.net.DatagramSocket.<init>(DatagramSocket.java:210)
at java.net.DatagramSocket.<init>(DatagramSocket.java:261)
at java.net.DatagramSocket.<init>(DatagramSocket.java:234)
at cn.soft.UpdReceDemo.main(UpdReceDemo.java:23)
请同学们帮忙解决下 看哪里出错了 |