简体   繁体   English

仅在第一次运行时收到来自 Java 的 UDP 消息

[英]UDP messages from Java are received only on first run

I'm using Java's DatagramSocket to send UDP messages from Java to a specific port on my localhost.我正在使用 Java 的 DatagramSocket 将 UDP 消息从 Java 发送到本地主机上的特定端口。 I listen to this port with netcat: nc -ul 9122 .我用 netcat 监听这个端口: nc -ul 9122

On the first run of my Java code (after starting nc) - the message is received and displayed on my shell.在我的 Java 代码的第一次运行(在启动 nc 之后)- 收到消息并显示在我的 shell 上。 On each other run - messages are not received.在彼此运行时 - 未收到消息。 Only restarting nc will do.只有重新启动 nc 才行。

This is my Java code:这是我的 Java 代码:

public static void main(String[] args) throws IOException, InterruptedException {
    byte[] buf = "Hi There\n".getBytes();

    InetAddress address = InetAddress.getLocalHost();
    DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 9122);

    DatagramSocket datagramSocket = new DatagramSocket();
    datagramSocket.connect(InetAddress.getLocalHost(), 9122);
    if(datagramSocket.isConnected()) {
        datagramSocket.send(packet);
        Thread.sleep(500);
        datagramSocket.send(packet);
        Thread.sleep(500);
        datagramSocket.send(packet);

    }
}

What do I miss?我想念什么? Thanks谢谢

This seems to be a feature of ncat .这似乎是ncat的一个功能。 After receiving one UDP packet, it only accepts packets from the same origin host and port.收到1个UDP包后,只接受来自同源主机和端口的包。 It is similar to a connection: an instance of ncat only handles packets from a single client.它类似于连接: ncat的一个实例只处理来自单个客户端的数据包。

When you start the Java program, it will select an arbitrary local port, and when you restart it you will get a different port.当您启动 Java 程序时,它将 select 一个任意本地端口,当您重新启动它时,您将获得一个不同的端口。 You can set fixed local port by passing it to the DatagramSocket constructor:您可以通过将其传递给DatagramSocket构造函数来设置固定的本地端口:

DatagramSocket datagramSocket = new DatagramSocket(12345);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM