I'm not using any selectors or anything like that. I just have a simple ServerSocketChannel listening and a SocketChannel connecting to it in blocking mode. I want to impose a timeout on the connection, but SocketChannel.socket().setSoTimeout() does not work.
I tried making a background thread sleep for 30 seconds and checking if a variable is still null (since it will block waiting to read into that variable) but I couldn't synchronize the variable properly in that I could not access the local variable in my anonymous class.
Are there other ways to accomplish this?
Update: I've worded my question wrong. I also want to have a timeout on read operations as well as the connection itself.
setSoTimeout() sets a read timeout, not a connect timeout, and for some reason it doesn't work at all on SocketChannels, even in blocking mode, and even with wrapped streams.
The method you are looking for is channel.socket().connect() with two arguments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With