-3

Say I start a simple UDP server: nc -u localhost 10000

And a simple UDP client: nc -ul 10000

Then is it possible, in Java, to receive the messages sent by the server without getting an "Address already in use" exception because there's already a client?

EDIT: here's the code I'm using:

DatagramSocket socket = new DatagramSocket(port);

new Thread(() -> {

    try {

        while(true) {

            byte[] receiveData = new byte[256];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            socket.receive(receivePacket);

            String message = new String( receivePacket.getData(), 0, receivePacket.getLength()).trim();
        }
    }
    catch (SocketException ignore) {}
    catch (IOException e) { e.printStackTrace(); }

}).start();

This leads to a java.net.BindException: Address already in use (bind failed).

Using this:

DatagramSocket socket = new DatagramSocket(null);
socket.setOption(SO_REUSEPORT, true);
socket.setOption(SO_REUSEADDR, true);

new Thread(() -> {

    try {

        while(true) {

            byte[] receiveData = new byte[256];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            socket.receive(receivePacket);

            String message = new String( receivePacket.getData(), 0, receivePacket.getLength()).trim();
        }
    }
    catch (SocketException ignore) {}
    catch (IOException e) { e.printStackTrace(); }

}).start();

Produces no exception but I won't receive the messages sent by the server.

EDIT 2: in the real situation, the server is broadcasting messages.

Tim Autin
  • 6,043
  • 5
  • 46
  • 76
  • Isn't the *client* connecting to the *server* at that given port? It is the *server* who listens to that port. The client will auto-assign a different port (>4096) for itself, then connect to the server, telling it where to send responses (since packages always contain both the sender and the receiver IP address and Port number as part of the package header). – Andreas Sep 07 '20 at 16:00
  • Well I red here and there that it works like that under the hood, but then why would I get an exception when trying to use that port again? – Tim Autin Sep 08 '20 at 07:53

1 Answers1

0

This should be possible by utilizing StandardSocketOptions.SO_REUSEPORT:

For datagram-oriented sockets the socket option usually allows multiple UDP sockets to be bound to the same address and port.

The Linux Kernel supports this since 3.9.

On Windows, you might need to utilize SO_REUSEADDR, but I'm not exactly sure.

Using SO_REUSEADDR
The SO_REUSEADDR socket option allows a socket to forcibly bind to a port in use by another socket.

Polygnome
  • 7,639
  • 2
  • 37
  • 57
  • Thanks. I tried (see my edits) but it doesn't work: I no longer get the exception but I do not get the messages sent by the server either. – Tim Autin Sep 08 '20 at 08:02