本文介绍了SocketChannel的超时不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 SocketChannel
并使其读/写方法超时。我试图为拥有我的 SocketChannel
的Socket设置超时,如下所示:
I want to use a SocketChannel
and to have a timeout for its read/write methods. I've tried to set a timeout for the Socket that owns my SocketChannel
like this:
channel.socket().setSoTimeout(TIMEOUT);
但这不起作用。还有其他解决方案吗?
but that doesn't work. Is there any other solution?
推荐答案
根据这个,SocketChannel不会因读取操作而超时,但是你可以从读取操作中获得此效果另一种方式。
According to this article, SocketChannel will not timeout for its read operation but you can get this effect from reading from the channel in another way.
SocketChannel socketChannel;
socketChannel.socket().setSocketTimeout(500);
InputStream inStream = socketChannel.socket().getInputStream();
ReadableByteChannel wrappedChannel = Channels.newChannel(inStream);
从wrappedChannel读取将根据您设置的socketTimeOut超时。
reading from the wrappedChannel will timeout according to the socketTimeOut you have set.
这篇关于SocketChannel的超时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!