这是发送文件
import java.net.*;
public class UdpSend
{
     public static void main(String [] args) throws Exception
     {
           DatagramSocket ds=new DatagramSocket();
           String str="hello world";
           DatagramPacket dp=new DatagramPacket(str.getBytes(),str.length(),InetAddress.getByName("192.168.0.213"),2222);
           ds.send(dp);
           ds.close();
     }
}这是接收文件
import java.net.*;
public class UdpRecv
{
    public static void main(String [] args) throws Exception
    {
        DatagramSocket ds=new DatagramSocket(2222);
        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.   

    不知道你是如何去运行这二个程序的!!
    如果你要在某一台机器中发送数据到192.168.0.213这台机器中,那就得先在192.168.0.213执行接收文件的那个程序;
    然后再在另一台机器上运行发送文件的程序。
    我的意思是要你分清先后顺序!!!
    如果你一开始就运行发送端的程序,然后再开启接收端的话,那么在接收端是接收不到数据的。
    因为从你的代码中可以看出,你仅仅发送了一次,而且发送的时间是相当快的!相反,如果先运行接收端,那么接收端在执行 ds.receive(dp); 的时候一直处于堵塞状态,直到有数据过来时才会执行后续语句!!!