Read timeout for an NIO SocketChannel? [duplicate]
Asked Answered
L

2

5

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?

Limitative answered 27/6, 2013 at 10:41 Comment(0)
F
13

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.

Ferraro answered 27/6, 2013 at 10:47 Comment(5)
I am using case 1. But as I understand, the select(timeout) is triggered if there are no channels selected at all. What I need to do is close an already connected SocketChannel if it does not send any readable data (i:e change from OP_ACCEPT to OP_READ) within a given time. Am I making sense?Limitative
Sure but you can't do that directly in case 1. You would have to keep track of the last read time for each channel and manipulate the select timeout so that the least recently read channel's timeout will expire if nothing happens, check all channels for timeouts, etc.Ferraro
I'm sorry what did you mean by 'manipulate the select timeout'?Limitative
As per this previous question case #2 will not work. It has an answer showing how to do it though.Please
@Limitative Err, change its value?Ferraro
G
1

I was looking for the same recommendation and could not find it easily - sharing it here.

There is a nice handler for netty called: ReadTimeoutHandler.

One can use it like that

channel.pipeline().addLast(new ReadTimeoutHandler(readTimeout));

it will drop io.netty.handler.timeout.ReadTimeoutException when failed to see any data doing the defined read timeout.

Greatuncle answered 15/9, 2017 at 8:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.