简体   繁体   中英

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. I listen to this port with netcat: nc -ul 9122 .

On the first run of my Java code (after starting nc) - the message is received and displayed on my shell. On each other run - messages are not received. Only restarting nc will do.

This is my Java code:

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 . After receiving one UDP packet, it only accepts packets from the same origin host and port. It is similar to a connection: an instance of ncat only handles packets from a single client.

When you start the Java program, it will select an arbitrary local port, and when you restart it you will get a different port. You can set fixed local port by passing it to the DatagramSocket constructor:

DatagramSocket datagramSocket = new DatagramSocket(12345);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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