日期:2014-05-20  浏览次数:20719 次

问个问题
import   java.io.IOException;
import   java.net.*;
class   Send   {

/**
  *   @param   args
  *   @throws   IOException  
  */
public   static   void   main(String[]   args)   throws   IOException  
{
DatagramSocket   ds=new   DatagramSocket();
byte[]   b= "hello   world ".getBytes();
DatagramPacket   dp=new   DatagramPacket(b,b.length,InetAddress.getLocalHost(),5555);
ds.send(dp);
ds.close();

}

}
import   java.io.IOException;
import   java.net.DatagramPacket;
import   java.net.DatagramSocket;


class   receive   {

/**
  *   @param   args
  *   @throws   IOException  
  */
public   static   void   main(String[]   args)   throws   IOException  
{
DatagramSocket   ds=new   DatagramSocket(5555);
byte[]   b=new   byte[1024];
DatagramPacket   dp=new   DatagramPacket(b,b.length);
ds.receive(dp);
System.out.println( "信息已收到 ");
ds.close();
}

}
帮我看看怎么我的主机在启动本机收包时好象进入死循环一样?


------解决方案--------------------
没错..你机器有问题吧,要不就是你只运行了接收程序,没运行发送程序,呵呵
------解决方案--------------------
receive方法产生一个“阻塞”。 “阻塞”是一个专业名词,它会产生一个内部循环,使程序暂停在这个地方,直到一个条件触发。

本机测试用:
DatagramPacket dp=new DatagramPacket(b,b.length,InetAddress.getByName( "127.0.0.1 "),5555);
可以接受到数据包。

用InetAddress.getLocalHost()柱塞,打印出我的本机地址feng/0.1.0.5。