gpt4 book ai didi

java - 如何用NIO设计Java服务器?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:29:37 24 4
gpt4 key购买 nike

假设我正在编写一个服务器。服务器接受客户端连接,从网络读取请求,处理它们并发回结果。还假设我想手动处理所有套接字的东西(只是作为练习)。

我希望有一个线程来处理带有 java.nio 非阻塞 API 的套接字。当它完全读取一个请求时,它开始异步处理它(使用Future 或将请求传递给另一个线程)并立即返回到选择器

当处理完成时,“套接字线程”应该接收到响应,通过套接字将其发送回客户端。但是我不知道该怎么做。

是不是上面的设计是错误的?您建议如何使用 java.nio 实现服务器?

最佳答案

当一个请求被放入队列,并且选择器线程在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);
}
}

关于java - 如何用NIO设计Java服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16120799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com