gpt4 book ai didi

java - 如何在具有 I/O 多路复用的 Java 服务器中异步处理请求?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:25:50 24 4
gpt4 key购买 nike

假设我正在编写一个 Java 服务器,它通过 TCP/IP 与客户端通信。

服务器使用I/O 多路复用。有一个线程 T0,它等待 selector 并处理客户端连接。例如,如果连接已准备好读取,则 T0 会从连接中读取数据。

假设服务器已经读取了传入的请求,现在它已准备好处理它。由于处理需要时间,请求在另一个线程 T1 中处理,T0 返回以等待选择器。

假设 T1 已经完成处理并创建了一个响应。现在 T0 应该开始写入对客户端连接的响应。所以我的问题是:T1 如何将响应发送到 T0

最佳答案

同一个线程 T1 应该读取、处理并将结果返回给客户端。

这里概述了如何使用 java nio api 在不将线程数与客户端数相关联的情况下执行此操作。

**//Thread T0** //wait for selection keys
...
Iterator it = selector.selectedKeys().iterator( );

while (it.hasNext( )) {
SelectionKey key = (SelectionKey) it.next();
// Is a new connection coming in?
if (key.isAcceptable( )) {
ServerSocketChannel server = (ServerSocketChannel) key.channel();
SocketChannel channel = server.accept()
// Set the new channel nonblocking
channel.configureBlocking (false);
// Register it with the selector
channel.register (selector, SelectionKey.OP_READ);
}

// Is there data to read on this channel?
if (key.isReadable( )) {
processRequest (key);
}

it.remove( );
}

...

ExecutorService service = Executors.newFixedThreadPool(50);
...
void processRequest(final SelectionKey key) {

**//Thread T1-T50** //deal with request
executorService.submit(new Runnable() {
SocketChannel channel = (SocketChannel) key.channel();

//read data from channel, process it and write back to the channel.
});
)
}

关于java - 如何在具有 I/O 多路复用的 Java 服务器中异步处理请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26085099/

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