通关Netty至NIO基础

3 篇文章 0 订阅
1 篇文章 0 订阅

NIO基础


一、三大组件简介


1、Channel和Buffer

Java NIO系统的核心在于:Channel(通道)和Buffer(缓冲区)。Channel表示打开IO设备的连接。如果需要使用NIO系统,则需要获取连接IO设备的通道以及用于存储数据的缓冲区。然后对缓冲区中的数据进行操作。换言之,通道负责传输,缓冲区负责存储

常见的Channel

  • FileChanne 【用于文件的读写】

  • DatagramChannel 【UDP】

  • SocketChannel 【TCP】 --> 客户端服务端都可以用

  • ServerSocketChannel 【TCP】-->专用于服务器

2、常用的buffer

  • ByteBuffer

    • MappedByteBuffer

    • DirectByteBuffer

    • HeapByteBuffer

  • ShortBuffer

  • IntBuffer

  • LongBuffer

  • FloatBuffer

  • DoubleBuffer

  • CharBuffer

image-20210819104143264.png

3、Selector


selector 单从字母案疑似不好理解,需要结合服务器设计的演化来理解

多线程版设计

20210418181918

⚠️多线程版的缺点

  • 内存占用高

  • 线程上下文切换成本高

    • 线程数并不是越多越好,前提是CPU要跟上。因为真正执行线程是由CPU决定的

  • 只适合连接数少的场景

    • 连接数过多会造成系统阻塞

线程池版

20210418181933

⚠️线程池的缺点

  • 阻塞模式下,线程仅能处理一个连接

    • 池中的线程获取任务后,*只有执行完毕当前任务后断开,才会继续获取下一个任务

    • 如果socket连接一直保持连接,则其他对应的线程就无法获取socket连接,造成阻塞

  • 仅适合短连接场景

    • 短连接:在建立连接发送请求后立刻断开。保持线程池中的线程可以快速处理其他连接

✅使用selector

20210418181947

selector的作用就是配合一个线程来管理多个channel,获取这些channel上发生的事件,这些channel工作在非阻塞模式下,当一个channel中没有任务时,可以去执行其他channel中的任务。适合连接数多,但流量较少的场景

若事件未就绪,调用selector的select()方法会阻塞线程,知道channel发生了就绪事件。这些事件就绪后,select方法就会返回这些事件交给thread来处理。

4、ByteBuffer


使用

  • 向buffer写入数据,例如调用 channel.read(buffer)

  • 调用flip()切换至读模式

    • flip()会使得buffer中的limit变为position,position变为0

  • 从buffer读取数据,例如调用buffer.get()

  • 调用clear()或者compact()切换至写模式

    • 调用clear()方法时position = 0,limit变为capacity

    • 调用compact()时,会将缓冲区中的未读数据压缩到缓冲区前面

  • 重复以上步骤

使用ByteBuffer读取文件中的内容

package com.atcode.nettydemo.heima;
​
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
​
public class BytebufferReadFile {
    public static void main(String[] args) {
      //获取FileChannel
        try (FileChannel channel = new FileInputStream("/Users/Desktop/111.txt").getChannel()){
          //获取ByteBuffer缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate(10);
            int hasNext = 0;
            StringBuilder  builder = new StringBuilder();
            while ((hasNext = channel.read(byteBuffer)) > 0) {
              //切换模式
                byteBuffer.flip();
              //判断buffer中是否还有数据,如果有则获取
                while (byteBuffer.hasRemaining()){
                    builder.append((char) byteBuffer.get());
                }
              /**
                  public final Buffer clear() {
                  position = 0;
                  limit = capacity;
                  mark = -1;
                  return this;
              }
              调用claer()方法,如上述源码,切换模式, position = 0; limit = capacity;
              */
                byteBuffer.clear();
            }
            System.out.println(builder.toString());
        } catch (IOException E){
​
        }
    }
}

ByteBuffer核心属性

  
ByteBuffer(int mark, int pos, int lim, int cap,   // package-private
                 byte[] hb, int offset)
    {
        super(mark, pos, lim, cap);
        this.hb = hb;
        this.offset = offset;
    }
  • int mark

    • 📝记录当前的position值。position改变后,可以通过reset()方法恢复到mark位置

  • int position

    • 📝写一个读写位置的索引。缓冲区的位置不能为负数,不能大于limit

  • int limit

    • 📝缓冲区的界限,位于limit后的数据不可读写,缓冲区的限制不能为负,并且不能大于其容量(capacity)

  • int capacity

    • 📝缓冲区的容量。通过构造函数赋予,一旦设置,无法更改

    以上四个属性必须满足以下要求

    mark <= position <= limit <= capacity

ByteBuffer核心方法

put() 方法

  • put()方法可以讲一个数据放到缓冲区中

  • 执行该操作后,position的值会 +1,指向下一个可以放入的位置。capacity = limit ,为缓冲区容量的值

20201109145709

filp()方法

  • flip()方法回切换缓冲区的操作模式。由读->写,由写 -> 读

  • 进行该操作后

    • 如果是写模式->读模式,position = 0 , limit 指向最后一个元素的下一个位置,capacity不变

    • 如果是读->写,则恢复为put()方法中的值

20201109145753

源码

 public final Buffer flip() {
        limit = position;
        position = 0;
        mark = -1;
        return this;
    }

get()方法

  • get()方法会读取缓冲区中的一个值

  • 执行该方法后,position会 + 1,如果超过了limit会抛出异常

  • 注意:get(i)不会改变position的值

20201109145822

rewind()

  • 只能在之都模式下使用

  • rewind()方法执行后,会回复position、limit、capacity的值,变为执行get()方法前的值

20201109145852

源码

 public final Buffer rewind() {
        position = 0;
        mark = -1;
        return this;
    }

clear()方法

  • clear()方法会将缓冲区中的各个属性恢复为最初的状态,position = 0, capacity = limit

  • 此时缓冲区的数据依然存在,处于“被遗忘”状态,下次进行写操作时会覆盖这些数据

20201109145905

源码

   
public final Buffer clear() {
        position = 0;
        limit = capacity;
        mark = -1;
        return this;
    }

mark()和reset()方法

  • mark()方法会将postion的值保存到mark属性中

    •   
       public final Buffer mark() {
              mark = position;
              return this;
          }

  • reset()方法会将position的值改为mark中保存的值

    • public final Buffer reset() {
              int m = mark;
              if (m < 0)
                  throw new InvalidMarkException();
              position = m;
              return this;
          }

compact()方法

此方法为ByteBuffer的方法,而不是Buffer的方法

  • compact会把未读完的数据向前压缩,然后切换到写模式

  • 数据前移后,原位置的值并未清零,写时会覆盖之前的值

代码演示

//netty依赖选用4.1.42.Final
      <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.42.Final</version>
        </dependency>
        
    package com.atcode.nettydemo.heima;
​
import io.netty.util.internal.MathUtil;
import io.netty.util.internal.StringUtil;
​
import java.nio.ByteBuffer;
​
public class ByteBufferdemo {
    private static final char[] BYTE2CHAR = new char[256];
    private static final char[] HEXDUMP_TABLE = new char[256 * 4 ];
    private static final String[] HEXPADDING = new String[16];
    private static final String[] HEXDUMP_ROWPREFIXES = new String[65536 >>> 4];
    private static final String[] BYTE2HEX = new String[256];
    private static final String[] BYTEPADDING = new String[16];
    static {
        final char[] DIGITS = "0123456789abcdef".toCharArray();
        for (int i = 0; i < 256; i++) {
            HEXDUMP_TABLE[i << 1] = DIGITS[i >>> 4 & 0x0F];
            HEXDUMP_TABLE[(i << 1) + 1] = DIGITS[i & 0x0F];
        }
​
        int i;
​
        /**
         * 生成十六进制转储填充的查找表
         */
        for (i = 0; i< HEXPADDING.length; i++){
            int padding =  HEXPADDING.length - 1;
            StringBuilder buf = new StringBuilder();
            for (int j = 0; j < padding; j++){
                buf.append("  ");
            }
            HEXPADDING[i] = buf.toString();
        }
​
        /**
         * 为每行的起始偏移头生成查找表(最多64KiB)。
         */
        for (i = 0; i < HEXDUMP_ROWPREFIXES.length; i++) {
            StringBuilder buf = new StringBuilder(12);
            buf.append(StringUtil.NEWLINE);
            buf.append(Long.toHexString(i << 4 & 0xFFFFFFFFL | 0x100000000L));
            buf.setCharAt(buf.length() - 9,'|');
            buf.append('|');
            HEXDUMP_ROWPREFIXES[i] = buf.toString();
        }
        /**
         * 生成字节到十六进制转储转换的查找表
          */
        for (i = 0; i < BYTE2HEX.length; i++) {
            BYTE2HEX[i] = ' ' + StringUtil.byteToHexStringPadded(i);
        }
        // Generate the lookup table for byte dump paddings
        for (i = 0; i < BYTEPADDING.length; i++) {
            int padding = BYTEPADDING.length - i;
            StringBuilder buf = new StringBuilder(padding);
            for (int j = 0; j < padding; j++) {
                buf.append(' ');
            }
            BYTEPADDING[i] = buf.toString();
        }
​
        // Generate the lookup table for byte-to-char conversion
        for (i = 0; i < BYTE2CHAR.length; i++) {
            if (i <= 0x1f || i >= 0x7f) {
                BYTE2CHAR[i] = '.';
            } else {
                BYTE2CHAR[i] = (char) i;
            }
        }
    }
​
    /**
     * 打印所有内容
     * @param buffer
     */
    public static void debugAll(ByteBuffer buffer) {
        int oldlimit = buffer.limit();
        buffer.limit(buffer.capacity());
        StringBuilder origin = new StringBuilder(256);
        appendPrettyHexDump(origin, buffer, 0, buffer.capacity());
        System.out.println("+--------+-------------------- all ------------------------+----------------+");
        System.out.printf("position: [%d], limit: [%d]\n", buffer.position(), oldlimit);
        System.out.println(origin);
        buffer.limit(oldlimit);
    }
​
    /**
     * 打印可读取内容
     * @param buffer
     */
    public static void debugRead(ByteBuffer buffer) {
        StringBuilder builder = new StringBuilder(256);
        appendPrettyHexDump(builder, buffer, buffer.position(), buffer.limit() - buffer.position());
        System.out.println("+--------+-------------------- read -----------------------+----------------+");
        System.out.printf("position: [%d], limit: [%d]\n", buffer.position(), buffer.limit());
        System.out.println(builder);
    }
​
    private static void appendPrettyHexDump(StringBuilder dump, ByteBuffer buf, int offset, int length) {
        if (MathUtil.isOutOfBounds(offset, length, buf.capacity())) {
            throw new IndexOutOfBoundsException(
                    "expected: " + "0 <= offset(" + offset + ") <= offset + length(" + length
                            + ") <= " + "buf.capacity(" + buf.capacity() + ')');
        }
        if (length == 0) {
            return;
        }
        dump.append(
                "         +-------------------------------------------------+" +
                        StringUtil.NEWLINE + "         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |" +
                        StringUtil.NEWLINE + "+--------+-------------------------------------------------+----------------+");
​
        final int startIndex = offset;
        final int fullRows = length >>> 4;
        final int remainder = length & 0xF;
​
        // Dump the rows which have 16 bytes.
        for (int row = 0; row < fullRows; row++) {
            int rowStartIndex = (row << 4) + startIndex;
​
            // Per-row prefix.
            appendHexDumpRowPrefix(dump, row, rowStartIndex);
​
            // Hex dump
            int rowEndIndex = rowStartIndex + 16;
            for (int j = rowStartIndex; j < rowEndIndex; j++) {
                dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
            }
            dump.append(" |");
​
            // ASCII dump
            for (int j = rowStartIndex; j < rowEndIndex; j++) {
                dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
            }
            dump.append('|');
        }
​
        // Dump the last row which has less than 16 bytes.
        if (remainder != 0) {
            int rowStartIndex = (fullRows << 4) + startIndex;
            appendHexDumpRowPrefix(dump, fullRows, rowStartIndex);
​
            // Hex dump
            int rowEndIndex = rowStartIndex + remainder;
            for (int j = rowStartIndex; j < rowEndIndex; j++) {
                dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
            }
            dump.append(HEXPADDING[remainder]);
            dump.append(" |");
​
            // Ascii dump
            for (int j = rowStartIndex; j < rowEndIndex; j++) {
                dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
            }
            dump.append(BYTEPADDING[remainder]);
            dump.append('|');
        }
​
        dump.append(StringUtil.NEWLINE +
                "+--------+-------------------------------------------------+----------------+");
    }
​
    private static void appendHexDumpRowPrefix(StringBuilder dump, int row, int rowStartIndex) {
        if (row < HEXDUMP_ROWPREFIXES.length) {
            dump.append(HEXDUMP_ROWPREFIXES[row]);
        } else {
            dump.append(StringUtil.NEWLINE);
            dump.append(Long.toHexString(rowStartIndex & 0xFFFFFFFFL | 0x100000000L));
            dump.setCharAt(dump.length() - 9, '|');
            dump.append('|');
        }
    }
​
    public static short getUnsignedByte(ByteBuffer buffer, int index) {
        return (short) (buffer.get(index) & 0xFF);
    }
}
​
​
​

调用ByteBuffer的方法

import java.nio.ByteBuffer;

public class TestByteBuffer {
        public static void main(String[] args) {
            ByteBuffer buffer = ByteBuffer.allocate(10);
            // 向buffer中写入1个字节的数据
            buffer.put((byte)97);
            // 使用工具类,查看buffer状态
            ByteBufferdemo.debugAll(buffer);

            // 向buffer中写入4个字节的数据
            buffer.put(new byte[]{98, 99, 100, 101});
            ByteBufferdemo.debugAll(buffer);

            // 获取数据
            buffer.flip();
            ByteBufferdemo.debugAll(buffer);
            System.out.println(buffer.get());
            System.out.println(buffer.get());
            ByteBufferdemo.debugAll(buffer);

            // 使用compact切换模式
            buffer.compact();
            ByteBufferdemo.debugAll(buffer);

            // 再次写入
            buffer.put((byte)102);
            buffer.put((byte)103);
            ByteBufferdemo.debugAll(buffer);
        }
}

字符串与ByteBuffer的相互转换

方法一

编码:字符串调用getByte方法获得byte数组,将byte数组放入ByteBuffer中

解码先调用ByteBuffer的flip方法,然后通过StandardCharsets的decoder方法解码

public static void main(String[] args) {
        String str1 = "hello";
        String str2 = "";
        ByteBuffer buffer1 = ByteBuffer.allocate(16);
        //把字符串放进缓冲区
        buffer1.put(str1.getBytes());
        ByteBufferdemo.debugAll(buffer1);
        //将缓冲区中的数据转为字符串。切换模式
        buffer1.flip();
        // 通过StandardCharsets解码,获取CharBuffer,再通过to
        str2 = StandardCharsets.UTF_8.decode(buffer1).toString();
        System.out.println(str2);
        ByteBufferdemo.debugAll(buffer1);

    }

方法二

编码:通过StandardCharsets的encode方法获得ByteBuffer,此时获得的ByteBuffer为读模式,无需通过flip切换模式

解码:通过StandardCharsets的decoder方法解码

public class Translate {
    public static void main(String[] args) {
        // 准备两个字符串
        String str1 = "hello";
        String str2 = "";

        // 通过StandardCharsets的encode方法获得ByteBuffer
        // 此时获得的ByteBuffer为读模式,无需通过flip切换模式
        ByteBuffer buffer1 = StandardCharsets.UTF_8.encode(str1);
        ByteBufferUtil.debugAll(buffer1);

        // 将缓冲区中的数据转化为字符串
        // 通过StandardCharsets解码,获得CharBuffer,再通过toString获得字符串
        str2 = StandardCharsets.UTF_8.decode(buffer1).toString();
        System.out.println(str2);
        ByteBufferUtil.debugAll(buffer1);
    }
}

方法三

编码:字符串调用getByte()方法获得字节数组,将字节数组传给ByteBuffer的wrap()方法,通过该方法获得ByteBuffer。同样无需调用flip方法切换为读模式

解码:通过StandardCharsets的decoder方法解码

public class Translate {
    public static void main(String[] args) {
        // 准备两个字符串
        String str1 = "hello";
        String str2 = "";

        // 通过StandardCharsets的encode方法获得ByteBuffer
        // 此时获得的ByteBuffer为读模式,无需通过flip切换模式
        ByteBuffer buffer1 = ByteBuffer.wrap(str1.getBytes());
        ByteBufferUtil.debugAll(buffer1);

        // 将缓冲区中的数据转化为字符串
        // 通过StandardCharsets解码,获得CharBuffer,再通过toString获得字符串
        str2 = StandardCharsets.UTF_8.decode(buffer1).toString();
        System.out.println(str2);
        ByteBufferUtil.debugAll(buffer1);
    }
}

粘包和半包

粘包

发送方在发送数据时,并不是一条一条地发送数据,而是将数据整合在一起,当数据达到一定的数量后再一起发送。这就会导致多条信息被放在一个缓冲区中被一起发送出去

半包

接收方的缓冲区的大小是有限的,当接收方的缓冲区满了以后,就需要将信息截断,等缓冲区空了以后再继续放入数据。这就会发生一段完整的数据最后被截断的现象

解决办法

  • 通过get(index)方法遍历ByteBuffer,遇到分隔符时进行特殊处理。注意:get(index)不会改变position的值

    1. 记录该段数据长度,以便于申请对应大小的缓冲区

    2. 将缓冲区中的数据通过get()方法写入到target中

  • 调用compact()方法切换模式,因为缓冲区中可能还存在未读取的数据

代码实例:

public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(32);
        buffer.put("hello,world\nIam zs\nho".getBytes());
        split(buffer);
        buffer.put("w are you\n".getBytes());
        split(buffer);
    }

    public static void split(ByteBuffer byteBuffer){
        byteBuffer.flip();
        for (int i = 0; i < byteBuffer.limit(); i++) {
            // 遍历寻找分隔符
            // get(i)不会移动position
             if (byteBuffer.get(i) == '\n'){
                 // 缓冲区长度
                 int length = i+1-byteBuffer.position();
                 // 将前面的内容重新写入构建的缓冲区
                 ByteBuffer target = ByteBuffer.allocate(length);
                 for (int j = 0;j < length;j++){
                     //将bytebuffer中的数据写道target中
                     target.put(byteBuffer.get());
                 }
                 ByteBufferdemo.debugAll(byteBuffer);
             }
        }
        byteBuffer.compact();
    }

网络编程

1、阻塞与非阻塞

阻塞

  1. 在阻塞模式下,相关方法都会导致线程暂停;一个方法的调用会影响另一个方法

    1. ServerSocketChannel.accept()会在没有连接建立时让线程暂停

    2. SocketChannel.read()会在通道中没有数据可读取时让线程暂停

    3. 阻塞的表现其实就是线程暂停,不占用CPU但是出于闲置状态

  2. 阻塞方法在单线程下无法工作,只能使用多线程支持

  3. 多线程下会有新的问题

    1. 32为的jvm一个线程320k,64位的jvm一个线程1024K,如果连接数过多必然导致OOM,并且会导致CPU切换线程频繁性能低下

    2. 可以采用线程池技术来集中管理线程。但是如果连接数过多依然有可能出现阻塞的情况。因此只适合短连接

实例代码

/** 服务端*/
public class Server {
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(16);
        try(ServerSocketChannel server = ServerSocketChannel.open()){
            server.bind(new InetSocketAddress(8080));
      			server.configureBlocking(false);//非阻塞模式
            ArrayList<SocketChannel> channels = new ArrayList<>();
            while (true){
                System.out.println("before connecting...");//非阻塞注释
                SocketChannel socketChannel = server.accept();//阻塞,线程停止运行
              /**
                 * 判断是否为空。非阻塞模式

                if (socketChannel != null){
                    System.out.println("after connecting ...");
                    channels.add(socketChannel);
                }
                 */
                System.out.println("after connecting ...");
                channels.add(socketChannel);
                for (SocketChannel channel : channels) {
                    System.out.println("before reading..."); //非阻塞注释
                    int read = channel.read(buffer);//非阻塞,线程仍然运行,若没有数据,则返回0 read = 0
                    buffer.flip();
                    ByteBufferdemo.debugAll(buffer);
                    buffer.clear();
                    System.out.println("after reading");
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

/** 客户端*/
  public static void main(String[] args) {
        try(SocketChannel socketChannel = SocketChannel.open()){
            socketChannel.connect(new InetSocketAddress("localhost",8080));
            System.out.println("waiting...");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

2、Selector

多路复用

单线程可以配合 Selector 完成对多个 Channel 可读写事件的监控,这称之为多路复用

  • 多路复用仅针对网络 IO,普通文件 IO 无法利用多路复用

  • 如果不用 Selector 的非阻塞模式,线程大部分时间都在做无用功,而 Selector 能够保证

    • 有可连接事件时才去连接

    • 有可读事件才去读取

    • 有可写事件才去写入

      • 限于网络传输能力,Channel 未必时时可写,一旦 Channel 可写,会触发 Selector 的可写事件

示例代码

public static void main(String[] args) {
        try(ServerSocketChannel server = ServerSocketChannel.open()){
            Selector selector = Selector.open();//创建selector
            ByteBuffer buffer = ByteBuffer.allocate(16);
            server.configureBlocking(false);//设置为非阻塞
            //SelectionKey 是事件发生后,通过它可以得到是什么事件和那个channel发生的事件
            /**
             * 多种事件:
             *  accept  会有连接请求时触发
             *  connect 是客户端连接建立后触发的事件
             *  read    客户端发送数据后服务端可进行读取的事件
             *  write    可写事件
             */
            SelectionKey sscKey = server.register(selector, 0,null);
            //只关注accept事件
            sscKey.interestOps(SelectionKey.OP_ACCEPT);
            log.info("register key:{}",sscKey);
            server.bind(new InetSocketAddress(8080));
            while (true){
                /**
                 * 看是否发生事件  select 没有事件线程阻塞,有事件才运行
                 * select  在事件未处理的时候,它不会阻塞,陷入死循环
                 */
                selector.select();
                //处理事件  selectedKeys() ->所有可用的事件集合()
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                //集合遍历删除需要用迭代器
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){  //
                    SelectionKey key  = iterator.next();
                    //处理key的时候要从seelctKeys集合中删除,因为第二次就不需要建立连接所以需要删除,发生集合只往里加,不会删除
                    iterator.remove();
                    log.debug("key:{}",key);
                    //区分事件类型
                    if (key.isAcceptable()) {
                        //如果是连接事件
                        //获取触发事件的channel
                        ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                        SocketChannel sc = channel.accept(); //连接事件
                        //读取事件
                        sc.configureBlocking(false);
                        //channel再一次注册到selector
                        SelectionKey scKey = sc.register(selector, 0, null);
                        //关注读事件
                        scKey.interestOps(SelectionKey.OP_READ);
                        log.debug("channel 连接 :{}",sc);
                        log.debug("scKey 连接 :{}",scKey);
                    } else if (key.isReadable()){
                        try {
                            SocketChannel channel = (SocketChannel)key.channel();//获取到触发事件的channel
                            ByteBuffer buffer1 = ByteBuffer.allocate(16);
                            int read = channel.read(buffer1);
                            buffer1.flip();
                            ByteBufferdemo.debugAll(buffer1);
                         	  iterator.remove();
                        } catch (IOException e) {
                            e.printStackTrace();
                            //客户端断开,需要将这个key取消,也就是从selectorKey集合中删除
                            key.cancel();//反注册,真正删除掉//事件取消;如果不处理事件需要需要否则会阻塞
                        }
                    }
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

步骤详解

  1. 构建选择器Selector

 Selector selector = Selector.open();//创建selector
  1. 将通道设置为非阻塞模式。并且注册到选择器中,然后设置需要关注的相应事件

    1. channel必须是非阻塞模式

    2. 可以绑定的事件

      1. connect 客户端连接成功触发

      2. accept 服务器端成功接受连接时触发

      3. read 当有数据可读时触发,

      4. write 当有数据可写时触发

     server.configureBlocking(false);//设置为非阻塞
     SelectionKey sscKey = server.register(selector, 0,null);
    //只关注accept事件
    sscKey.interestOps(SelectionKey.OP_ACCEPT);
    1. 通过Selector监听事件,来获取就绪的通道数量,若没有通道就绪则线程阻塞

      1. 阻塞知道绑定事件发生

         selector.select();//看是否发生事件  select 没有事件线程阻塞,有事件才运行
      1. 阻塞直到绑定事件发生,或是超时(ms)

           public abstract int select(long timeout)
      1. 不会阻塞,不管有没有事件,立刻返回。然后根据返回值检查是否有事件

        public abstract int selectNow() throws IOException;
      2. 获取所有事件并处理

         //处理事件  selectedKeys() ->所有可用的事件集合()
        Set<SelectionKey> selectionKeys = selector.selectedKeys();
        //集合遍历删除需要用迭代器
        Iterator<SelectionKey> iterator = selectionKeys.iterator();
        1. 事件发生后能否不处理

          事件发生后,要么处理,要么取消(cancel),不能什么都不做,否则下次该事件仍会触发,这是因为 nio 底层使用的是水平触发

         //处理key的时候要从seelctKeys集合中删除,因为第二次就不需要建立连接所以需要删除,发生集合只往里加,不会删除
        iterator.remove();

3、使用及Accpet事件

4、Read事件

5、Write事件

6、优化

未完......

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Go语言(也称为Golang)是由Google开发的一种静态强类型、编译型的编程语言。它旨在成为一门简单、高效、安全和并发的编程语言,特别适用于构建高性能的服务器和分布式系统。以下是Go语言的一些主要特点和优势: 简洁性:Go语言的语法简单直观,易于学习和使用。它避免了复杂的语法特性,如继承、重载等,转而采用组合和接口来实现代码的复用和扩展。 高性能:Go语言具有出色的性能,可以媲美C和C++。它使用静态类型系统和编译型语言的优势,能够生成高效的机器码。 并发性:Go语言内置了对并发的支持,通过轻量级的goroutine和channel机制,可以轻松实现并发编程。这使得Go语言在构建高性能的服务器和分布式系统时具有天然的优势。 安全性:Go语言具有强大的类型系统和内存管理机制,能够减少运行时错误和内存泄漏等问题。它还支持编译时检查,可以在编译阶段就发现潜在的问题。 标准库:Go语言的标准库非常丰富,包含了大量的实用功能和工具,如网络编程、文件操作、加密解密等。这使得开发者可以更加专注于业务逻辑的实现,而无需花费太多时间在底层功能的实现上。 跨平台:Go语言支持多种操作系统和平台,包括Windows、Linux、macOS等。它使用统一的构建系统(如Go Modules),可以轻松地跨平台编译和运行代码。 开源和社区支持:Go语言是开源的,具有庞大的社区支持和丰富的资源。开发者可以通过社区获取帮助、分享经验和学习资料。 总之,Go语言是一种简单、高效、安全、并发的编程语言,特别适用于构建高性能的服务器和分布式系统。如果你正在寻找一种易于学习和使用的编程语言,并且需要处理大量的并发请求和数据,那么Go语言可能是一个不错的选择。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值