How to achieve timeout handling in blocking DatagramChannel without using selectors

datagram, java, nio, udp

Solution

Apparently the issue of not being able to timeout is not a bug with DatagramChannel, but that:

Not a bug. The read methods in SocketChannel (and DatagramChannel) do not support timeouts. If you need the timeout functionality then use the read methods of the associated Socket (or DatagramSocket) object.

Link.

Problem

I get a feeling that I am missing something really obvious here. The overall structure of my system makes me want to use a blocking DatagramChannel without Selectors, in order to keep things simple. I am trying to achieve timeout handling by setting a timeout on the socket, but this seems to have no effect. This pseudoized code gives a hint of what I am trying to achieve. ``` DatagramChannel channel = DatagramChannel.open(); channel.socket().bind(some address); channel.socket().setSoTimeout(3000); channel.send(outBuffer, peerAddress); channel.receive(inBuffer); ``` On the other side, I have a UDP server that gives five quick responses, and then, for testing purposes, delays about five seconds before delivering the sixth response. The delay does not trigger a SocketTimeoutException. Why is that? The timeout set on the socket does not seem to be taken into consideration when calling channel.receive. Regards, Fredrik

Original source