Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read timeout for an NIO SocketChannel? [duplicate]

What is the best way to set a timeout to close a NIO SocketChannel if there is no data is received for a certain period after the connection is established?

like image 958
Sam Avatar asked Sep 02 '26 21:09

Sam


1 Answers

Either:

  1. You are using a Selector, in which case you have a select timeout which you can play with, and if it goes off (select(timeout) returns zero) you close all the registered channels, or

  2. You are using blocking mode, in which case you might think you should be able to call Socket.setSoTimeout() on the underlying socket (SocketChannel.socket()), and trap the SocketTimeoutException that is thrown when the timeout expires during read(), but you can't, because it isn't supported for sockets originating as channels, or

  3. You are using non-blocking mode without a Selector, in which case you need to change to case (1).

So you either need to use case (1) or a java.net.Socket directly.

like image 50
user207421 Avatar answered Sep 05 '26 11:09

user207421



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!