我想使用 SocketChannel
并为其读/写方法设置超时。我试过为拥有我的 SocketChannel
的套接字设置超时,如下所示:
channel.socket().setSoTimeout(TIMEOUT);
但这行不通。还有其他解决办法吗?
最佳答案
根据这个article , SocketChannel 不会对其读取操作超时,但您可以通过另一种方式从 channel 读取来获得此效果。
SocketChannel socketChannel;
socketChannel.socket().setSocketTimeout(500);
InputStream inStream = socketChannel.socket().getInputStream();
ReadableByteChannel wrappedChannel = Channels.newChannel(inStream);
从 wrappedChannel 读取会根据您设置的 socketTimeOut 超时。
关于java - SocketChannel 的超时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2866557/