我们有一个谈话到另一台主机通过套接字类,它看起来是这样的:除非主机关闭,然后一个SocketChannel超时上与插座使用NIO的SocketChannel
SocketChannel sc = SocketChannel.open(new InetSocketAddress(HOST, PORT));
sc.configureBlocking(true);
...
sc.write(...)
sc.read(...)
这个类的伟大工程。永远打开块。我试着这样做,使这个超时如下:
SocketChannel = SocketChannel.open();
sc.configureBlocking(false);
boolean result = socketChannel.connect(new InetSocketAddress(HOST, PORT));
if (!result) {
long startTime = System.currentTimeMillis();
while (!socketChannel.finishConnect()) {
if (System.currentTimeMillis() - startTime< 1000) {
// keep trying
Thread.sleep(100);
} else {
// FAILED!
enabled = false;
return;
}
}
}
// SUCCESS!
socketChannel.configureBlocking(true);
enabled = true
那么出于某种原因finishConnect()永远阻塞的时候我会想到是不是在所有的块。有任何想法吗?
阻塞是NIO的默认行为,因此即使大多数人认为它是关于非阻塞IO,您也不需要将其设置为BTW。 AFAIK你不能改变阻塞模式。 – 2013-05-04 05:27:36
@PeterLawrey当然可以。这就是'configureBlocking()'的用途。 – EJP 2013-05-04 10:00:23
@EJP感谢您的纠正。我没有看到它在一个区块中使用,并在以后切换到另一个区块。 – 2013-05-04 11:25:13