【发布时间】:2015-02-10 20:29:17
【问题描述】:
我无法理解 NIO 的工作原理。这是一个示例代码:
// Create the server socket channel
ServerSocketChannel server = ServerSocketChannel.open();
// nonblocking I/O
server.configureBlocking(false);
// host-port 8000
server.socket().bind(new java.net.InetSocketAddress(host,8000));
// Create the selector
Selector selector = Selector.open();
// Recording server to selector (type OP_ACCEPT)
server.register(selector,SelectionKey.OP_ACCEPT);
while (true) {
selector.select(); // blocking operation
Iterator it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey selKey = (SelectionKey) it.next();
// THE MOST INTRIGUING PART HERE!!!
if (selKey.isAcceptable()) {
ServerSocketChannel ssChannel = (ServerSocketChannel) selKey.channel();
SocketChannel sc = ssChannel.accept();
}
it.remove();
}
}
这里我有几个问题:
- selKey.channel() 返回一个 ServerSocketChannel 是否与我们一开始使用 ServerSocketChannel.open() 创建的通道完全相同?如果不是,那是什么?
- 更重要的问题:在大多数其他教程中 selKey.channel();步骤被跳过,他们只是使用 SocketChannel client = server.accept();例如这里:http://www.onjava.com/pub/a/onjava/2002/09/04/nio.html?page=2 和这里:http://www.developer.com/java/article.php/10922_3837316_2/Non-Blocking-IO-Made-Possible-in-Java.htm 那么,server.accept() 如何知道我们处理的当前密钥?
-
在http://www.developer.com/java/article.php/10922_3837316_2/Non-Blocking-IO-Made-Possible-in-Java.htm 中,他们甚至建议在新线程中接受频道。我猜可能会出现以下情况。
key1 someClient1 acceptable key2 someClient2 not acceptable key3 someClient3 acceptable startThread1 startThread3 scheduler decides to give time to thread3 instead of thread1 thread3 -> socket.accept() <- actually accepts client1 thread1 -> socket.accept() <- actually accepts client3
那么,您能否解释一下 selector 如何与 ServerSocketChannel 和 accept 方法配对使用?因为我不明白#accept 接受客户的顺序以及该顺序与 selectedKeys 的关系。
-
我可以简单地执行以下操作吗:
int availableClients = 0; while (it.hasNext()) { SelectionKey selKey = (SelectionKey) it.next(); if (selKey.isAcceptable()) { ++availableClients; } it.remove(); } for (int i = 0; i < availableClients; ++i) { SocketChannel sc = server.accept(); doSomething(sc); }
【问题讨论】:
标签: java sockets network-programming nio nonblocking