作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
假设我正在编写一个服务器。服务器接受客户端连接,从网络读取请求,处理它们并发回结果。还假设我想手动处理所有套接字的东西(只是作为练习)。
我希望有一个线程来处理带有 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/
我是一名优秀的程序员,十分优秀!