how to create multiple UDP Datagram channels/streams on same local/src address

555 views Asked by At

I have to receive data from diff clients on same port of server. I want to create separate channels for each client for this purpose and receive data on each of them.

I am exploring all the options available to design this.

Option 1 : Listen on a single socket and process the data coming from various devices.

Option 2 : Create multiple channels on same src address (in server) with diff remote addresses (of clients) and use a NIO selector to process data on these channels.

Option 1 seems bit risky as the remote devices are huge in number. And I can't seem to implement option 2. I get bind exception even though I am using setReuseAddress() API before binding the channel.

Can anyone help me here? Or if there is any better way to design this. I have explored other questions on stackoverflow but still I am not able to get proper understanding on whether it's feasible or not.

1

There are 1 answers

0
Ben Barkay On

A single UDP socket could service many clients.

Seeing as UDP is a stateless protocol, you could read from all of these clients without creating a thread (or channel) for each client.

int yourPort = // ...

try (DatagramSocket socket = new DatagramSocket(new InetSocketAddress("0.0.0.0", yourPort))) {
    byte[] buf = new byte[65535];
    DatagramPacket packet = new DatagramPacket(buf, 0, buf.length);
    while (socket.isBound() && !socket.isClosed()) {
        // The packets received here are from all sources, not just a single source
        socket.receive(packet);

        // If we simply send that same packet, without modifying anything, it
        // will echo the same content to whoever sent that packet
        socket.send(packet);
    }
} catch (IOException e) {
    // probably a good idea to close/re-bind here..
}

The snippet above will theoretically handle any amount of clients, requiring only a single thread to do so. There is no such concept of session channels in UDP.

You could (and probably should) copy the received data and process it outside of this loop to maximize the utilized network throughput. This is something that you would have to do independent of what strategy you choose.

There is no reason that the above implementation would be significantly less performant than other ways.


  • Creating multiple sockets won't increase your throughput.
  • The idea behind setReuseAddress is to allow many registrations to the same multicast endpoint. Not to increase throughput.
  • You may increase your receive and send buffers if you believe that these might be overflown by traffic, by using DatagramSocket#setReceiveBufferSize and DatagramSocket#setSendBufferSize.