ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

NIO,selector学习笔记

2021-12-24 13:01:31  阅读:139  来源: 互联网

标签:java NIO read 笔记 selector key import SocketChannel


package cn.itcast.netty.c1;


import com.sun.org.apache.bcel.internal.generic.Select;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import static cn.itcast.netty.c1.ByteBufferUtil.debugAll;

@Slf4j
public class ServerSocketSelectorDemo {
    public static void main(String[] args) throws IOException {
        // 先打开一个channel
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // 使用selector去多路复用
        Selector selector = Selector.open();
        // 给ssc 绑定端口号
        ssc.bind(new InetSocketAddress(8080));
        ssc.configureBlocking(false);
        // 2.将通道注册进入selector中
        SelectionKey sscKey = ssc.register(selector, 0, null);
        // ServerSocketChannel 只关心连接事件
        sscKey.interestOps(SelectionKey.OP_ACCEPT);
        // 分配缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(36);
        //等待链接
        while(true){
            log.info("没有事件发生,阻塞等待.....");
            // 事件驱动的话,select没有事件发生的时候是会阻塞到这里,不至于空转
            selector.select();
            // 获取到监听的事件集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while(iterator.hasNext()){
                // 获取所有的监听key,当然此时只有serversocketchannel
                SelectionKey key = iterator.next();
                // 这里为什么要移除呢,因为,事件发生后,selectionKey必须要处理,不处理会一直监听。而处理过后,并不会从集合中删除该key,而是把监听的accept/read事件给删除了。
                iterator.remove();
                // 如果此key关注的是accept事件的话
                if(key.isAcceptable()){
                    log.info("有连接事件进来接受链接.....");
                    // 可以获取到2注册进来的channel
                    ServerSocketChannel sschanel = (ServerSocketChannel) key.channel();
                    // 获取后可以接受链接了
                    SocketChannel sc = sschanel.accept();
                    sc.configureBlocking(false);
                    // 把客户端的sc也注册进入selector
                    SelectionKey clientKey = sc.register(selector, 0, null);
                    // 此key只关注,read事件
                    clientKey.interestOps(SelectionKey.OP_READ);
                }else if(key.isReadable()){
                    log.info("有read事件进来读取数据.....");
                    // 获取客户端的chanel
                    SocketChannel cchanel = (SocketChannel) key.channel();
                    ByteBuffer buffer1 = ByteBuffer.allocate(36);
                    try{
                        int read = cchanel.read(buffer1);
                        log.info("read==={}",read);
                        // 如果正常关闭,read会返回-1
                        if(read == -1){
                            key.cancel();
                        }else{
                            buffer1.flip();
                            System.out.println(Charset.defaultCharset().decode(buffer1));
                            debugAll(buffer1);
                        }
                    }catch (Exception ex){
                        key.cancel();
                        ex.printStackTrace();
                    }
                }
            }
        }
    }
}
package cn.itcast.netty.c1;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;

@Slf4j
public class SocketChanelDemo {
    public static void main(String[] args) throws IOException {
        // 打开一个客户端chanel
        SocketChannel ch = SocketChannel.open();
        // 连接到ServerSocket
        ch.connect(new InetSocketAddress("localhost",8080));
        System.out.println("正在连接");
    }
}

标签:java,NIO,read,笔记,selector,key,import,SocketChannel
来源: https://blog.csdn.net/skyshowshow/article/details/122125447

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有