加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

如何使用I / O多路复用在Java服务器中异步处理请求?

发布时间:2020-12-15 04:22:42 所属栏目:Java 来源:网络整理
导读:假设我正在编写一个 Java服务器,它通过TCP / IP与客户端通信. 服务器使用I / O多路复用.有一个单独的线程T0,它等待选择器并处理客户端连接.例如,如果连接已准备好进行读取,则T0将从连接中读取数据. 假设服务器已读取传入请求,现在已准备好处理它.由于处理需
假设我正在编写一个 Java服务器,它通过TCP / IP与客户端通信.

服务器使用I / O多路复用.有一个单独的线程T0,它等待选择器并处理客户端连接.例如,如果连接已准备好进行读取,则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.
    });
)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读