Read timeout for an NIO SocketChannel? [duplicate]

妖精的绣舞 提交于 2019-12-06 06:33:00

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/17340970/read-timeout-for-an-nio-socketchannel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!