簡答題:從您對接受的連接感興趣的操作列表中刪除OP_CONNECT
- 接受的連接已經連接。
我設法重現的問題,這可能正是發生了什麼你:上述服務器接收到一個連接,非常的連接退出第一select()
後不會阻塞
import java.net.*;
import java.nio.channels.*;
public class MyNioServer {
public static void main(String[] params) throws Exception {
final ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(true);
serverChannel.socket().bind(new InetSocketAddress("localhost", 12345));
System.out.println("Listening for incoming connections");
final SocketChannel clientChannel = serverChannel.accept();
System.out.println("Accepted connection: " + clientChannel);
final Selector selector = Selector.open();
clientChannel.configureBlocking(false);
final SelectionKey clientKey = clientChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT);
System.out.println("Selecting...");
System.out.println(selector.select());
System.out.println(selector.selectedKeys().size());
System.out.println(clientKey.readyOps());
}
}
,也沒有鑰匙隨時準備運營。我不知道爲什麼Java會以這種方式行事,但似乎很多人都被這種行爲所困擾。
結果與Windows XP上Sun的JVM 1.5.0_06以及Linux 2.6上Sun的JVM 1.5.0_05和1.4.2_04相同。
感謝您的回答。這顯然是select的行爲中的一個反常現象,但它很容易解決。 – 2008-11-06 09:55:54