Search code examples
javanetwork-programmingudpdatagram

Handle unreachable UDP ports with Java sockets


I'm using a Java DatagramSocket to stream data to multiple different clients. As I handle the list of currently registered clients myself, I only bind the socket to the server port and don't connect to any specific client.

However, by not using connect(), I lose the ability of the DatagramSocket to react to ICMP notifications of an unreachable port, which are sent if one of the clients dies and doesn't get the chance to properly unregister with the server.

Is there any way to get that behavior back? I thought of using one DatagramSocket per client, but that doesn't seem to be feasible as they would all have to be bound to the same port on the server (impossible in UDP, as far as I know).

I'm aware that there is no guarantee that my server ever sees the ICMP messages and I'll implement some kind of timeout mechanism to handle that, but reacting to the ICMP messages would allow me to immediately stop transmitting to any host that doesn't have a client running, which seems like a nice thing to do to the streaming client users.


Solution

  • If you want reliable point to point connections, I would use TCP.

    However if you want UDP, I would suggest your clients send heartbeats so the publisher can timeout subscribers which stop sending. I assume you don't need the connection to be reliable, but it can still be worth the subscribers sending packets back to the publisher.