Reputation: 937
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
Upvotes: 0
Views: 469
Reputation: 111269
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);
Upvotes: 1