NIO消息边界问题处理

本文介绍了TCP/IP通信中如何处理消息边界问题,包括使用固定长度、分隔符和TLV格式等策略,以及面对不同情况如缓冲区大小与消息大小不匹配时的解决方案。同时,文章还探讨了服务器端处理可读事件的机制,展示了读取和写入操作的示例代码,强调了ByteBuffer的合理分配和管理对于高并发连接的重要性。
摘要由CSDN通过智能技术生成


问题描述

@Slf4j
public class EchoServer4 {

    public static void main(String[] args) throws IOException {
        // 创建selector,可以管理多线程
        Selector selector = Selector.open();
        ServerSocketChannel ssc= ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8080));
        //设置为非阻塞
        ssc.configureBlocking(false);
        //注册ServerSocketChannel到selector里面
        SelectionKey sscKey = ssc.register(selector, 0, null);
        log.debug("sscKey:{}",sscKey);
        //关注accept事件
        sscKey.interestOps(SelectionKey.OP_ACCEPT);
        while (true){
            //如果没有连接,那么会阻塞在这里
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                //删除key
                iterator.remove();
                log.debug("key:{}",key);
                //连接事件
                if (key.isAcceptable()) {
                    //获取对应的channel
                    ServerSocketChannel channel = (ServerSocketChannel)key.channel();
                    SocketChannel sc = channel.accept();
                    sc.configureBlocking(false);
                    //注册SocketChannel
                    SelectionKey scKey = sc.register(selector, 0, null);
                    //关注读取事件
                    scKey.interestOps(SelectionKey.OP_READ);
                    log.debug("{}",sc);
                    //读取事件
                }else if(key.isReadable()){
                    //ctrl+alt+t   try-catch快键
                    try {
                        SocketChannel channel =(SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(4);
                        int read = channel.read(buffer);
                        if(read==-1){
                            key.cancel();
                        }else {
                            buffer.flip();
                            System.out.println(Charset.defaultCharset().decode(buffer));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        key.cancel();
                    }
                }

            }
        }
    }
}

ByteBuffer buffer = ByteBuffer.allocate(4);这里buffer容量设置小。第一次客户端发送“hi!”,正常打印,第二次发送“中国”,出现乱码和换行。
在这里插入图片描述

原因分析:一个buffer4个字节。中文UTF-8编码,每个汉字3个字节,总共6个字节。索引多次读取的时候,第一次读取中+国的三分之一。第二次完整读取国的剩余部分。所以国没有读取完整,出现了乱码。


提示:以下是本篇文章正文内容,下面案例可供参考

一、处理消息边界

示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。

  1. ByteBufeer较小,但是消息比较大
  2. ByteBufeer较大,消息比较小。会出现半包现象
  3. ButeBuffer较小,但是容纳了多个消息。此时会出现黏包现象

解决思路:

  1. 一种思路是固定消息长度,数据包大小一样,服务器按预定长度读取,缺点是浪费带宽

比如客户端和服务端约定,客户端每次发送1024字节。服务端每次接受1024字节。客户端超出的下一次发送,并且补齐不足的部分,使满足1024.
在这里插入图片描述

  1. 另一种思路是按分隔符拆分,缺点是效率低
    比如每次遇到\n,代表一条消息。
  2. TLV 格式,即 Type 类型、Length 长度、Value 数据,类型和长度已知的情况下,就可以方便获取消息大小,分配合适的 buffer,缺点是 buffer 需要提前分配,如果内容过大,则影响 server 吞吐量
  • Http 1.1 是 TLV 格式
  • Http 2.0 是 LTV 格式
客户端1 服务器 ByteBuffer1 ByteBuffer2 发送 01234567890abcdef3333\r 第一次 read 存入 01234567890abcdef 扩容 拷贝 01234567890abcdef 第二次 read 存入 3333\r 01234567890abcdef3333\r 客户端1 服务器 ByteBuffer1 ByteBuffer2

使用分隔符解决

@Slf4j
public class EchoServer4 {

    public static void main(String[] args) throws IOException {
        // 创建selector,可以管理多线程
        Selector selector = Selector.open();
        ServerSocketChannel ssc= ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8080));
        //设置为非阻塞
        ssc.configureBlocking(false);
        //注册ServerSocketChannel到selector里面
        SelectionKey sscKey = ssc.register(selector, 0, null);
        log.debug("sscKey:{}",sscKey);
        //关注accept事件
        sscKey.interestOps(SelectionKey.OP_ACCEPT);
        while (true){
            //如果没有连接,那么会阻塞在这里
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                //删除key
                iterator.remove();
                log.debug("key:{}",key);
                //连接事件
                if (key.isAcceptable()) {
                    //获取对应的channel
                    ServerSocketChannel channel = (ServerSocketChannel)key.channel();
                    SocketChannel sc = channel.accept();
                    sc.configureBlocking(false);
                    //注册SocketChannel
                    SelectionKey scKey = sc.register(selector, 0, null);
                    //关注读取事件
                    scKey.interestOps(SelectionKey.OP_READ);
                    log.debug("{}",sc);
                    //读取事件
                }else if(key.isReadable()){
                    //ctrl+alt+t   try-catch快键
                    try {
                        SocketChannel channel =(SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(16);
                        int read = channel.read(buffer);
                        if(read==-1){
                            key.cancel();
                        }else {
                           split(buffer);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        key.cancel();
                    }
                }

            }
        }
    }

    private static void split(final ByteBuffer buffer) {
        buffer.flip();
        for(int i=0;i<buffer.limit();i++){
            if (buffer.get(i)=='\n') {
                //遇到\n,表示一个完整的语句。写入的buffer
                int length=i+1-buffer.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                //将数据写入target
                for (int j = 0; j < target.limit(); j++) {
                    // 将buffer中的数据写入target中
                    target.put(buffer.get());
                }
                debugAll(target);
            }
        }
        //读取完毕之后读取剩余的部分,不能使用clear。clear会从头开始的
        buffer.compact();
    }

}

1、处理消息边界-容量超出

但是客户端长度大于buffer的长度之后,就会产生多次读取,最终只会读取到最后一次的数据。

在这里插入图片描述

2、处理消息边界-附件与扩容

@Slf4j
public class EchoServer5 {

    public static void main(String[] args) throws IOException {
        // 创建selector,可以管理多线程
        Selector selector = Selector.open();
        ServerSocketChannel ssc= ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8080));
        //设置为非阻塞
        ssc.configureBlocking(false);
        //注册ServerSocketChannel到selector里面
        SelectionKey sscKey = ssc.register(selector, 0, null);
        log.debug("sscKey:{}",sscKey);
        //关注accept事件
        sscKey.interestOps(SelectionKey.OP_ACCEPT);
        while (true){
            //如果没有连接,那么会阻塞在这里
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                //删除key
                iterator.remove();
                log.debug("key:{}",key);
                //连接事件
                if (key.isAcceptable()) {
                    //获取对应的channel
                    ServerSocketChannel channel = (ServerSocketChannel)key.channel();
                    SocketChannel sc = channel.accept();
                    sc.configureBlocking(false);
                    ByteBuffer buffer = ByteBuffer.allocate(16);
                    //注册SocketChannel。将buffer和channel对应
                    SelectionKey scKey = sc.register(selector, 0, buffer);
                    //关注读取事件
                    scKey.interestOps(SelectionKey.OP_READ);
                    log.debug("{}",sc);
                    //读取事件
                }else if(key.isReadable()){
                    //ctrl+alt+t   try-catch快键
                    try {
                        SocketChannel channel =(SocketChannel) key.channel();
                        //获取关联的附件
                        ByteBuffer buffer =(ByteBuffer) key.attachment();
                        int read = channel.read(buffer);
                        if(read==-1){
                            key.cancel();
                        }else {
                           split(buffer);
                           if(buffer.position()==buffer.limit()){
                               ByteBuffer newBuffer = ByteBuffer.allocate(buffer.capacity() * 2);
                               buffer.flip();
                               newBuffer.put(buffer);
                               key.attach(newBuffer);
                           }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        key.cancel();
                    }
                }

            }
        }
    }

    private static void split(final ByteBuffer buffer) {
        buffer.flip();
        for(int i=0;i<buffer.limit();i++){
            if (buffer.get(i)=='\n') {
                //遇到\n,表示一个完整的语句。写入的buffer
                int length=i+1-buffer.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                //将数据写入target
                for (int j = 0; j < target.limit(); j++) {
                    // 将buffer中的数据写入target中
                    target.put(buffer.get());
                }
                debugAll(target);
            }
        }
        //读取完毕之后读取剩余的部分,不能使用clear。clear会从头开始的
        buffer.compact();
    }

}

在这里插入图片描述在这里插入图片描述

3、处理消息边界-bytebuffer大小分配

ByteBuffer 大小分配
  • 每个 channel 都需要记录可能被切分的消息,因为 ByteBuffer 不能被多个 channel 共同使用,因此需要为每个 channel 维护一个独立的 ByteBuffer
  • ByteBuffer 不能太大,比如一个 ByteBuffer 1Mb 的话,要支持百万连接就要 1Tb 内存,因此需要设计大小可变的 ByteBuffer
    • 一种思路是首先分配一个较小的 buffer,例如 4k,如果发现数据不够,再分配 8k 的 buffer,将 4k buffer 内容拷贝至 8k buffer,优点是消息连续容易处理,缺点是数据拷贝耗费性能,参考实现 http://tutorials.jenkov.com/java-performance/resizable-array.html
    • 另一种思路是用多个数组组成 buffer,一个数组不够,把多出来的内容写入新的数组,与前面的区别是消息存储不连续解析复杂,优点是避免了拷贝引起的性能损耗

二、处理可写事件

server端

public class WriteServer {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);

        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT);

        ssc.bind(new InetSocketAddress(8080));

        while (true){
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey sscKey = iterator.next();
                iterator.remove();
                if (sscKey.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    SelectionKey scKey = sc.register(selector, 0, null);
                    scKey.interestOps(SelectionKey.OP_READ);
                    StringBuilder sb=new StringBuilder();
                    for(int i=0;i<300000000;i++){
                        sb.append("a");
                    }
                    ByteBuffer buffer = Charset.defaultCharset().encode(sb.toString());
                    int write = sc.write(buffer);
                    System.out.println(write);
                    if (buffer.hasRemaining()){
                        scKey.interestOps(scKey.interestOps()+SelectionKey.OP_WRITE);
                        scKey.attach(buffer);
                    }
                }else if(sscKey.isWritable()){
                    ByteBuffer buffer = (ByteBuffer) sscKey.attachment();
                    SocketChannel sc = (SocketChannel) sscKey.channel();
                    int write = sc.write(buffer);
                    System.out.println("实际写入字节:" + write);
                    if (!buffer.hasRemaining()) { // 写完了
                        sscKey.interestOps(sscKey.interestOps() - SelectionKey.OP_WRITE);
                        sscKey.attach(null);
                    }
                }
            }
        }
    }
}

客户端

public class WriteClient {

    public static void main(String[] args) throws IOException {
        SocketChannel open = SocketChannel.open();
        open.connect(new InetSocketAddress("localhost",8080));
        int read=0;
        while (true){
            ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);
            read += open.read(buffer);
            System.out.println(read);
            buffer.clear();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值