如何使用NIO设计Java服务器?

3
假设我正在编写一个服务器。 服务器接受客户端连接,从网络中读取请求,处理它们并发送结果。 假设我想手动处理所有这些套接字操作(只是为了练习)。
我希望使用非阻塞的java.nio API来处理套接字,并使用单个线程处理它们。 当它完全读取一个请求时,它将开始异步地处理它(使用Future或将请求传递给另一个线程),并立即返回到选择器。
当处理完成后,“套接字线程”应该接收响应以将其通过套接字发送回客户端。 然而,我不知道如何做到这一点。
这是否意味着上述设计是错误的? 您如何建议使用java.nio实现服务器?
1个回答

2

当请求被放入队列中,而选择器线程正在 selector.select() 中时,请调用 selector.wakeup()。选择器线程按照以下方式执行循环:

while (selector.isOpen() && !Thread.interrupted()) {
    for (;;) {
        Request r=queue.poll(); // requests can be both to read and write
        if (r==null) {
            break;
        }
        processRequest(r);
    }

    selector.select(); // wait for next event

    // Iterate over the set of keys for which events are available
    Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
    while (selectedKeys.hasNext()) {
        SelectionKey key = selectedKeys.next();
        selectedKeys.remove();
        processKey(key);
    }
}

太好了!selector.wakeup 似乎是我正在寻找的 API。 - Michael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接