jdk nio多并发 长连接

java nio


一、服务器

1、初始化

(1)创建多路复用器selector

(2)创建服务器socket管道serversSocketChannel

(3)serversocket绑定服务端口

(4)设置服务器socket管道的阻塞方式为非阻塞式

(5)为服务器socket管道绑定selector

        Selector selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(port));
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

2、端口监听和处理

(1)监听多路复用器selector

(2)获取客户端请求状态集selectedKeys

 

(3)循环处理每笔请求,判断每笔请求的状态并根据状态做相应处理

        while (true) {
        
            int n = selector.select();//监听多路复用器,看是否有客户端请求
            if (n <= 0)
                continue;
         
            Iterator<SelectionKey> it = selector.selectedKeys().iterator();//获取客户端请求状态集

            while (it.hasNext()) {
                SelectionKey key = it.next();
                //System.out.print(".");
             
                if (key.isAcceptable()) {//如果状态为acceptable,则为新连接
                    SocketChannel channel = ((ServerSocketChannel) key
                            .channel()).accept();//获取socket管道
                    if (channel != null) {
                        // new connection from client, register it
                        channel.configureBlocking(false);
                        channel.register(selector, SelectionKey.OP_READ);

                       /**

                       */自定义处理逻辑

                       */

                       */
                }

                if (key.isReadable()) {//如果状态为Readable,则该已建立连接,读取请求内容
                    
                    SocketChannel channel = (SocketChannel) key.channel();
                    m_buffer.clear(); // empty the buffer
                    while ((count = channel.read(m_buffer)) > 0) {
                          //读取请求流并作处理
                    }

                    if (count < 0) {//如果出现socket关闭标示,则关闭管道
                        // Close channel on EOF.
                        channel.close();
                    }
                }
                it.remove();//请求处理完后清除请求集
            }
        }

二、客户端

以任何方式发起TCP连接和请求即可 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值