NIO SocketChannel connect with timeout

Socket got a connect(address, timeout) method a couple JRE versions ago.
We also got NIO with SocketChannel so we could use Selectors…
but SocketChannel’s connect method doesn’t take a timeout parameter.

Does somebody need to be shot, or is there a way to use Channels AND connect to a socket with timeout?

???

socketChannel.socket().setSoTimeout(ms);

Or did you mean something else?

Completely off the top of my head …

“you don’t need a timeout, because SC’s do a non-blocking Connect, and send a message to the Selector with message type CONNECTED when that becomes the case” ???

both of the above, you don’t need a timeout for your program’s flow sake, to avoid having something trying to connect forever it’s already constraint by the setSoTimeout(value).

setSoTimeout() doesn’t seem to effect connect() (on windows here at least). SO_TIMEOUT maps to SO_SNDTIMEO and SO_RCVTIMEO in the underlying setsockopt() which only effect receive and send.

Whether or not the socket is in blocking mode you do still want it to stop attempting to connect once packets are failing for a set period - 20 seconds by default. Just because you’re not blocked by it doesn’t mean you wouldn’t like it to stop trying eventually and tell you that it failed. It’d still be nice to be able to configure this like you can directly on the socket.

Would:


socketChannel.socket().connect(address, ms);

Work?

Kev

Yeah, what Kev said…

setSoTimeout() doesn’t affect connect(), and I want the selector to notify me sooner that the connection isn’t happening.

channel.socket().connect(addr, timeout) might work…