java 未收到数据报套接字(本地主机)

java datagram socket not received (localhost)

这是一个常见问题,但我似乎无法解决这个问题,这不是防火墙的问题,我确保 Intellij 已获得授权。

UDP 发件人:

public static void main(String[] args){
    Timer timer = new Timer();
    try {
        InetAddress ip = InetAddress.getLocalHost();
        int port = 9850;
        byte[] buffer = new byte[100];
        DatagramPacket packet = new DatagramPacket(buffer, 100, ip, port);

        try {
            DatagramSocket socket = new DatagramSocket(port, ip);
            timer.schedule(new TimerTask() {
                               @Override
                               public void run() {
                                   System.out.println("will send !");
                                   try {
                                       socket.send(packet);
                                   }catch (IOException e){
                                       e.printStackTrace();
                                       return;
                                   }
                                   System.out.println("was sent !");
                               }
                           },500, 500);
        } catch (SocketException e) {
            e.printStackTrace();
            return;
        }
    }catch (UnknownHostException e){
        e.printStackTrace();
        return;
    }
}

UDP 接收器

    public static void main(String[] args) {
    int port = 8888;
    byte[] buffer = new byte[100];
    DatagramPacket packet = new DatagramPacket(buffer, 100);

    try {
        DatagramSocket socket = new DatagramSocket(port);

        while(true) {
            try {
                System.out.println("ready to receive");
                socket.receive(packet);
                System.out.println("received a packet");
            }catch (IOException e){
                e.printStackTrace();
                return;
            }
        }
    }catch(SocketException e){
        e.printStackTrace();
        return;
    }
}

数据包已发送,发送方确实显示"will send/was sent"但接收方没有收到任何东西,它被阻止并且只显示"ready to receive"

ps:没关系套接字没有关闭...

您不需要使用 while(true),因为方法 DatagramPacket.receive 将阻塞直到收到数据报。

问题的原因可能是一侧与另一侧的端口不同

仔细查看您正在使用的对 DatagramSocketDatagramPacket 的各种调用,因为您在滥用它们。

在 Sender 程序中,您是 "construct[ing] a datagram packet for sending packets of length length to the specified port number on the specified host." 然后您是 "creat[ing] a datagram socket, bound to the specified local address"。当您使用相同的端口和 InetAddr 时,您实际上是在将数据包发送到您列出的相同地址。

在 Receiver 程序中,您 "construct[] a datagram socket and bind[] it to the specified port on the local host machine." 这一次,您将它绑定到与发送它的端口不同的端口。 (8888 与 9850,您将数据包发送到的地址)。

对于发送方,尝试通过调用 DatagramSocket() 创建绑定到随机端口的套接字。对于接收方,更改套接字,使其绑定到发送方尝试将其发送到的相同编号端口(例如 9850)