好像不能发送,代码很简单,按理说先运行send,在运行recv,就会显示出"Hello World",但是我运行了,为何却接收不到,都在本机测试的UdpSend.javaimport java.net.*;
public class UdpSend 
{
public static void main(String[] args) throws Exception
{
// TODO: Add your code here
DatagramSocket ds=new DatagramSocket();
String str="Hello World";
DatagramPacket dp=new DatagramPacket(str.getBytes(),str.length(),
InetAddress.getByName("192.168.1.150"),3000);
ds.send(dp);
System.out.println("Success");
ds.close();
}
}
UdpRecvimport java.net.*;
public class UdpRecv {
public static void main(String[] args) throws Exception{
// TODO: Add your code here
DatagramSocket ds=new DatagramSocket();
byte[] buf=new byte [1024];
DatagramPacket dp=new DatagramPacket(buf,1024);
ds.receive(dp);
String strRecv=new String(dp.getData(),0,dp.getLength())+
"from"+
dp.getAddress().getHostAddress()+":"+dp.getPort();
System.out.println(strRecv);
ds.close();
}
}

解决方案 »

  1.   

    你的代码在运行完send时,你的UdpRecv还没有运行,当你send完,你的UdpSend就已经结束了,而此时再运行UdpRecv,肯定收不到了。
      

  2.   

    http://blog.csdn.net/arielxp/archive/2004/06/23/24316.aspx
    这里面有代码,讲得很不错。
      

  3.   

    那么我先运行Recv在运行Send就可以了吗?好像也不行啊
      

  4.   

    还有那个blog的网址好像打不开阿
      

  5.   

    Recv最好写成Thread或者实现Runnable接口
      

  6.   

    你的Recv写的有问题,需要在运行之后来一个循环来接受sender,你把接受数据包的代码,放在一个无限循环里试试.你可以搜索这方面的信息.
      

  7.   

    DatagramSocket 没有设置监听3000端口啊
    DatagramSocket ds=new DatagramSocket(3000);