20-Netty TCP 粘包和拆包及解决方案

TCP粘包和拆包的基本介绍TCP是面向连接的, 面向流的, 提供可靠性服务, 收发两端(客户端和服务器端) 都有一一成对的Socket,因此发送端为了将多个发给接收端的包, 更有效的发给对方, 使用了优化算法(Nagle算法),将多次间隔较小且数据量小的数据,合并成一个大的数据块,然后进行封包, 这样做虽然提高了效率,但是接收端就难于分辨出完整的数据包了,因为面向流的通信是无消息保护边界的由于TCP无消息保护边界, 需要在接收端处理消息边界问题, 也就是我们所说的粘包,拆包问题,看一张图示意图TCP粘包,拆包图解

20-Netty TCP 粘包和拆包及解决方案

对图的说明

假设客户端分别发送了两个数据包D1和D2给服务端, 由于服务端一次读取到字节数是不确定的,故有可能存在以下四种情况

服务端分别两次读取到了两个独立的数据包, 分别是D1 和 D2, 没有粘包和拆包服务端一次接收到了两个数据包D1和D2粘在了一起,称之为TCP粘包服务端分两次读取到了数据包, 第一次读取到了完整的D1包和D2包的部分内容, 第二次读取到了D2包的剩余部分, 称之为TCP拆包服务器分两次读取到了数据包, 第一次读取到了D1包的部分内容D1_1, 第二次读取到了D1包的剩余部分D1_2, 和完整的D2包TCP粘包和拆包现象实例

在编写Netty程序时, 如果没有做处理,就会发生粘包和拆包问题

看一个具体的实例

NettyServer

代码语言:javascript代码运行次数:0运行复制

package com.dance.netty.netty.tcp;import io.netty.bootstrap.ServerBootstrap;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.*;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioServerSocketChannel;import java.nio.charset.StandardCharsets;import java.util.UUID;public class NettyServer {    public static void main(String[] args) {        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);        NioEventLoopGroup workerGroup = new NioEventLoopGroup();        try {            ServerBootstrap serverBootstrap = new ServerBootstrap();            serverBootstrap.group(bossGroup,workerGroup)                    .channel(NioServerSocketChannel.class)                    .option(ChannelOption.SO_BACKLOG, 128)                    .childOption(ChannelOption.SO_KEEPALIVE, true)                    .childHandler(new ChannelInitializer() {                        @Override                        protected void initChannel(SocketChannel ch) throws Exception {                            ChannelPipeline pipeline = ch.pipeline();                            pipeline.addLast(new NettyServerHandler());                        }                    });            ChannelFuture sync = serverBootstrap.bind("127.0.0.1", 7000).sync();            System.out.println("server is ready ......");            sync.channel().closeFuture().sync();        } catch (Exception e) {            e.printStackTrace();        } finally {            bossGroup.shutdownGracefully();            workerGroup.shutdownGracefully();        }    }    static class NettyServerHandler extends SimpleChannelInboundHandler {        private int count = 0;        @Override        protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {            byte[] bytes = new byte[msg.readableBytes()];            msg.readBytes(bytes);            count++;            System.out.println("服务器第"+count+"次接收到来自客户端的数据:" + new String(bytes, StandardCharsets.UTF_8));            // 服务器回送数据给客户端 回送随机的UUID给客户端            ctx.writeAndFlush(Unpooled.copiedBuffer(UUID.randomUUID().toString(),StandardCharsets.UTF_8));        }        @Override        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {            ctx.close();            cause.printStackTrace();        }    }}

NettyClient

代码语言:javascript代码运行次数:0运行复制

package com.dance.netty.netty.tcp;import io.netty.bootstrap.Bootstrap;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.*;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;import java.nio.charset.StandardCharsets;public class NettyClient {    public static void main(String[] args) {        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();        try {            Bootstrap bootstrap = new Bootstrap();            bootstrap.group(eventExecutors)                    .channel(NioSocketChannel.class)                    .handler(new ChannelInitializer() {                        @Override                        protected void initChannel(SocketChannel ch) throws Exception {                            ChannelPipeline pipeline = ch.pipeline();                            pipeline.addLast(new NettyClientHandler());                        }                    });            ChannelFuture sync = bootstrap.connect("127.0.0.1", 7000).sync();            sync.channel().closeFuture().sync();        } catch (Exception e) {            e.printStackTrace();        } finally {            eventExecutors.shutdownGracefully();        }    }    static class NettyClientHandler extends SimpleChannelInboundHandler {        private int count = 0;        @Override        public void channelActive(ChannelHandlerContext ctx) throws Exception {            // 连续发送10条数据            for (int i = 0; i < 10; i++) {                ctx.writeAndFlush(Unpooled.copiedBuffer("hello,server!" + i, StandardCharsets.UTF_8));            }        }        @Override        protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {            byte[] bytes = new byte[msg.readableBytes()];            msg.readBytes(bytes);            // 接收服务器的返回            count++;            System.out.println("客户端第"+count+"次接收服务端的回送:" + new String(bytes, StandardCharsets.UTF_8));        }        @Override        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {            ctx.close();            cause.printStackTrace();        }    }}

执行结果

Server

代码语言:javascript代码运行次数:0运行复制

log4j:WARN No appenders could be found for logger (io.netty.util.internal.logging.InternalLoggerFactory).log4j:WARN Please initialize the log4j system properly.log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.server is ready ......服务器第1次接收到来自客户端的数据:hello,server!0hello,server!1hello,server!2hello,server!3hello,server!4hello,server!5hello,server!6hello,server!7hello,server!8hello,server!9服务器第1次接收到来自客户端的数据:hello,server!0服务器第2次接收到来自客户端的数据:hello,server!1服务器第3次接收到来自客户端的数据:hello,server!2hello,server!3hello,server!4服务器第4次接收到来自客户端的数据:hello,server!5hello,server!6服务器第5次接收到来自客户端的数据:hello,server!7hello,server!8hello,server!9

Client1

代码语言:javascript代码运行次数:0运行复制

客户端第1次接收服务端的回送:84653e99-0e7f-431d-a897-c215af959a3b

Client2

代码语言:javascript代码运行次数:0运行复制

客户端第1次接收服务端的回送:6f3b0e79-2f40-4066-bb6b-80f988ecec116b6bbd94-b345-46d6-8d36-a114534331a850628e04-ece1-4f58-b684-d30189f6cf26b2139027-6bda-4d40-9238-9fc0e59bc7a64b568ffe-f616-4f48-8f1c-05ecf3e817ee

分析:

服务器启动后到server is ready ……

第一个客户端启动后 TCP将10次发送直接封包成一次直接发送,所以导致了服务器一次就收到了所有的数据,产生了TCP粘包,拆包的问题

第二客户端启动后 TCP将10次发送分别封装成了5次请求,产生粘包,拆包问题

TCP粘包和拆包解决方案使用自定义协议 + 编解码器来解决关键就是要解决 服务器每次读取数据长度的问题, 这个问题解决, 就不会出现服务器多读或少读数据的问题,从而避免TCP粘包和拆包TCP粘包, 拆包解决方案实现要求客户端发送5个Message对象, 客户端每次发送一个Message对象服务器端每次接收一个Message, 分5次进行解码, 每读到一个Message, 会回复一个Message对象给客户端

20-Netty TCP 粘包和拆包及解决方案

新建协议MessageProtocol代码语言:javascript代码运行次数:0运行复制

package com.dance.netty.netty.protocoltcp;/** * 消息协议 */public class MessageProtocol {    private int length;    private byte[] content;    public MessageProtocol() {    }    public MessageProtocol(int length, byte[] content) {        this.length = length;        this.content = content;    }    public int getLength() {        return length;    }    public void setLength(int length) {        this.length = length;    }    public byte[] getContent() {        return content;    }    public void setContent(byte[] content) {        this.content = content;    }}

新建编码器代码语言:javascript代码运行次数:0运行复制

package com.dance.netty.netty.protocoltcp;import io.netty.buffer.ByteBuf;import io.netty.channel.ChannelHandlerContext;import io.netty.handler.codec.MessageToByteEncoder;/** * 自定义协议编码器 */public class MyMessageProtocolEncoder extends MessageToByteEncoder {    @Override    protected void encode(ChannelHandlerContext ctx, MessageProtocol msg, ByteBuf out) throws Exception {//        System.out.println("自定义协议-->开始编码");        // 开始发送数据        out.writeInt(msg.getLength()); // 优先发送长度,定义边界        out.writeBytes(msg.getContent());//        System.out.println("自定义协议---->编码完成");    }}

新建解码器代码语言:javascript代码运行次数:0运行复制

package com.dance.netty.netty.protocoltcp;import io.netty.buffer.ByteBuf;import io.netty.channel.ChannelHandlerContext;import io.netty.handler.codec.ByteToMessageDecoder;import java.util.List;public class MyMessageProtocolDecoder extends ByteToMessageDecoder {    @Override    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception {//        System.out.println("自定义协议-->开始解码");        // 获取定义的边界长度        int length = in.readInt();        if(in.readableBytes() >= length){            // 根据长度读取数据            byte[] bytes = new byte[length];            in.readBytes(bytes);            // 反构造成MessageProtocol            MessageProtocol messageProtocol = new MessageProtocol(length, bytes);            out.add(messageProtocol);//            System.out.println("自定义协议---->解码完成");        }else{            // 内容长度不够        }    }}

新建服务器端代码语言:javascript代码运行次数:0运行复制

package com.dance.netty.netty.protocoltcp;import io.netty.bootstrap.ServerBootstrap;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.*;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioServerSocketChannel;import java.nio.charset.StandardCharsets;import java.util.UUID;public class NettyServer {    public static void main(String[] args) {        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);        NioEventLoopGroup workerGroup = new NioEventLoopGroup();        try {            ServerBootstrap serverBootstrap = new ServerBootstrap();            serverBootstrap.group(bossGroup,workerGroup)                    .channel(NioServerSocketChannel.class)                    .option(ChannelOption.SO_BACKLOG, 128)                    .childOption(ChannelOption.SO_KEEPALIVE, true)                    .childHandler(new ChannelInitializer() {                        @Override                        protected void initChannel(SocketChannel ch) throws Exception {                            ChannelPipeline pipeline = ch.pipeline();                            // 加入自定义协议编解码器                            pipeline.addLast(new MyMessageProtocolDecoder());                            pipeline.addLast(new MyMessageProtocolEncoder());                            pipeline.addLast(new NettyServerHandler());                        }                    });            ChannelFuture sync = serverBootstrap.bind("127.0.0.1", 7000).sync();            System.out.println("server is ready ......");            sync.channel().closeFuture().sync();        } catch (Exception e) {            e.printStackTrace();        } finally {            bossGroup.shutdownGracefully();            workerGroup.shutdownGracefully();        }    }    static class NettyServerHandler extends SimpleChannelInboundHandler {        private int count = 0;        @Override        protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {            byte[] bytes = msg.getContent();            count++;            System.out.println("服务器第"+count+"次接收到来自客户端的数据:" + new String(bytes, StandardCharsets.UTF_8));            // 服务器回送数据给客户端 回送随机的UUID给客户端            byte[] s = UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8);            ctx.writeAndFlush(new MessageProtocol(s.length,s));        }        @Override        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {            ctx.close();            cause.printStackTrace();        }    }}

新建客户端代码语言:javascript代码运行次数:0运行复制

package com.dance.netty.netty.protocoltcp;import io.netty.bootstrap.Bootstrap;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.*;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;import java.nio.charset.StandardCharsets;public class NettyClient {    public static void main(String[] args) {        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();        try {            Bootstrap bootstrap = new Bootstrap();            bootstrap.group(eventExecutors)                    .channel(NioSocketChannel.class)                    .handler(new ChannelInitializer() {                        @Override                        protected void initChannel(SocketChannel ch) throws Exception {                            ChannelPipeline pipeline = ch.pipeline();                            // 加入自定义分割符号//                            ByteBuf delimiter = Unpooled.copiedBuffer("rn".getBytes());//                            pipeline.addFirst(new DelimiterBasedFrameDecoder(8192, delimiter));                            // 添加自定义协议编解码器                            pipeline.addLast(new MyMessageProtocolDecoder());                            pipeline.addLast(new MyMessageProtocolEncoder());                            pipeline.addLast(new NettyClientHandler());                        }                    });            ChannelFuture sync = bootstrap.connect("127.0.0.1", 7000).sync();            sync.channel().closeFuture().sync();        } catch (Exception e) {            e.printStackTrace();        } finally {            eventExecutors.shutdownGracefully();        }    }    static class NettyClientHandler extends SimpleChannelInboundHandler {        private int count = 0;        @Override        public void channelActive(ChannelHandlerContext ctx) throws Exception {            // 连续发送10条数据            for (int i = 0; i < 10; i++) {                String msg = "今天天气冷, 打火锅" + i;                byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);                // 使用自定义协议                MessageProtocol messageProtocol = new MessageProtocol(bytes.length, bytes);                ctx.writeAndFlush(messageProtocol);            }        }        @Override        protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {            byte[] bytes = msg.getContent();            // 接收服务器的返回            count++;            System.out.println("客户端第"+count+"次接收服务端的回送:" + new String(bytes, StandardCharsets.UTF_8));        }        @Override        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {            ctx.close();            cause.printStackTrace();        }    }}

测试

发送10次

服务器端

代码语言:javascript代码运行次数:0运行复制

log4j:WARN No appenders could be found for logger (io.netty.util.internal.logging.InternalLoggerFactory).log4j:WARN Please initialize the log4j system properly.log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.server is ready ......服务器第1次接收到来自客户端的数据:今天天气冷, 打火锅0......服务器第10次接收到来自客户端的数据:今天天气冷, 打火锅9

客户端

代码语言:javascript代码运行次数:0运行复制

log4j:WARN No appenders could be found for logger (io.netty.util.internal.logging.InternalLoggerFactory).log4j:WARN Please initialize the log4j system properly.log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.客户端第1次接收服务端的回送:a6b69f1c-daba-435a-802a-c19a6350ca94......客户端第10次接收服务端的回送:5af5c297-8668-48aa-b8c4-35656142f591

ok,没有问题, 但是真的没有问题吗?答案是有问题

FAQ

发送1000次

修改客户端发送消息数量代码语言:javascript代码运行次数:0运行复制

@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {    // 连续发送10条数据    for (int i = 0; i < 1000; i++) {        ......    }}

重新测试

服务器端

代码语言:javascript代码运行次数:0运行复制

log4j:WARN No appenders could be found for logger (io.netty.util.internal.logging.InternalLoggerFactory).log4j:WARN Please initialize the log4j system properly.log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.server is ready ......服务器第1次接收到来自客户端的数据:今天天气冷, 打火锅0......服务器第31次接收到来自客户端的数据:今天天气冷, 打火锅30服务器第32次接收到来自客户端的数据:今天天气冷, 打火锅31io.netty.handler.codec.DecoderException: java.lang.NegativeArraySizeException    at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:459)    at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265)    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340)    at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1412)    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:943)    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:141)    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:645)    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:580)    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:497)    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:459)    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:886)    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)    at java.lang.Thread.run(Thread.java:748)Caused by: java.lang.NegativeArraySizeException    at com.dance.netty.netty.protocoltcp.MyMessageProtocolDecoder.decode(MyMessageProtocolDecoder.java:17)    at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489)    at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428)    ... 16 moreio.netty.handler.codec.DecoderException: java.lang.IndexOutOfBoundsException: readerIndex(1022) + length(4) exceeds writerIndex(1024): PooledUnsafeDirectByteBuf(ridx: 1022, widx: 1024, cap: 1024)    at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:459)    at io.netty.handler.codec.ByteToMessageDecoder.channelInputClosed(ByteToMessageDecoder.java:392)    at io.netty.handler.codec.ByteToMessageDecoder.channelInputClosed(ByteToMessageDecoder.java:359)    at io.netty.handler.codec.ByteToMessageDecoder.channelInactive(ByteToMessageDecoder.java:342)    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:245)    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:231)    at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:224)    at io.netty.channel.DefaultChannelPipeline$HeadContext.channelInactive(DefaultChannelPipeline.java:1407)    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:245)    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:231)    at io.netty.channel.DefaultChannelPipeline.fireChannelInactive(DefaultChannelPipeline.java:925)    at io.netty.channel.AbstractChannel$AbstractUnsafe$8.run(AbstractChannel.java:822)    at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163)    at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:404)    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:463)    at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:886)    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)    at java.lang.Thread.run(Thread.java:748)Caused by: java.lang.IndexOutOfBoundsException: readerIndex(1022) + length(4) exceeds writerIndex(1024): PooledUnsafeDirectByteBuf(ridx: 1022, widx: 1024, cap: 1024)    at io.netty.buffer.AbstractByteBuf.checkReadableBytes0(AbstractByteBuf.java:1403)    at io.netty.buffer.AbstractByteBuf.readInt(AbstractByteBuf.java:786)    at com.dance.netty.netty.protocoltcp.MyMessageProtocolDecoder.decode(MyMessageProtocolDecoder.java:14)    at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489)    at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428)    ... 17 more

what ? 直接报错了, 数组下标越界, 读索引1022 + 长度4 > 写缩影1024了

这个是什么问题呢 ? 我看网上关于这个BUG的解决方案很少,基本没有, 好多都是贴问题的, 我翻了将近1个小时,才找到一个大佬写的一篇文章解决了, 感谢大佬

博客地址:

代码语言:javascript代码运行次数:0运行复制

https://blog.csdn.net/u011035407/article/details/80454511

问题描述:

面试猫 面试猫

AI面试助手,在线面试神器,助你轻松拿Offer

面试猫 352 查看详情 面试猫

这样在刚开始的工作中数据包传输没有问题,不过数据包的大小超过512b的时候就会抛出异常了。

解决方案

配合解码器DelimiterBasedFrameDecoder一起使用,在数据包的末尾使用换行符n表示本次数据包已经结束,当DelimiterBasedFrameDecoder把数据切割之后,再使用ByteToMessageDecoder实现decode方法把数据流转换为Message对象。

我们在ChannelPipeline加入DelimiterBasedFrameDecoder解码器

客户端和服务器端都加

代码语言:javascript代码运行次数:0运行复制

//使用n作为分隔符pipeline.addLast(new LoggingHandler(LogLevel.INFO));pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));

在MessageToByteEncoder的实现方法encode()增加out.writeBytes(new byte[]{‘n’});

代码语言:javascript代码运行次数:0运行复制

//在写出字节流的末尾增加n表示数据结束out.writeBytes(new byte[]{'n'});

这时候就可以愉快的继续处理数据了。等我还没有高兴半天的时候,问题又来了。还是一样的问题

等等等,,,怎么又报错了,不是已经加了黏包处理了吗??,解决问题把,首先看解析的数据包结构

代码语言:javascript代码运行次数:0运行复制

         +-------------------------------------------------+         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |+--------+-------------------------------------------------+----------------+|00000000| 01 01 01 00 00 00 06 00 00 01 0a 7b 22 69 64 22 |...........{"id"||00000010| 3a 33 2c 22 75 73 65 72 6e 61 6d 65 22 3a 22 31 |:3,"username":"1||00000020| 38 35 30 30 33 34 30 31 36 39 22 2c 22 6e 69 63 |8500340169","nic||00000030| 6b 6e 61 6d 65 22 3a 22 e4 bb 96 e5 9b 9b e5 a4 |kname":"........||00000040| a7 e7 88 b7 22 2c 22 72 6f 6f 6d 49 64 22 3a 31 |....","roomId":1||00000050| 35 32 37 32 33 38 35 36 39 34 37 34 2c 22 74 65 |527238569474,"te||00000060| 61 6d 4e 61 6d 65 22 3a 22 e4 bf 84 e7 bd 97 e6 |amName":".......||00000070| 96 af 22 2c 22 75 6e 69 74 73 22 3a 7b 22 75 6e |..","units":{"un||00000080| 69 74 31 22 3a 7b 22 78 22 3a 31 30 2e 30 2c 22 |it1":{"x":10.0,"||00000090| 79 22 3a 31 30 2e 30 7d 2c 22 75 6e 69 74 32 22 |y":10.0},"unit2"||000000a0| 3a 7b 22 78 22 3a 31 30 2e 30 2c 22 79 22 3a 31 |:{"x":10.0,"y":1||000000b0| 30 2e 30 7d 2c 22 75 6e 69 74 33 22 3a 7b 22 78 |0.0},"unit3":{"x||000000c0| 22 3a 31 30 2e 30 2c 22 79 22 3a 31 30 2e 30 7d |":10.0,"y":10.0}||000000d0| 2c 22 75 6e 69 74 34 22 3a 7b 22 78 22 3a 31 30 |,"unit4":{"x":10||000000e0| 2e 30 2c 22 79 22 3a 31 30 2e 30 7d 2c 22 75 6e |.0,"y":10.0},"un||000000f0| 69 74 35 22 3a 7b 22 78 22 3a 31 30 2e 30 2c 22 |it5":{"x":10.0,"||00000100| 79 22 3a 31 30 2e 30 7d 7d 2c 22 73 74 61 74 75 |y":10.0}},"statu||00000110| 73 22 3a 31 7d 0a                               |s":1}.          |+--------+-------------------------------------------------+----------------+

接收到的数据是完整的没错,但是还是报错了,而且数据结尾的字节的确是0a,转化成字符就是n没有问题啊。

在ByteToMessageDecoder的decode方法里打印ByteBuf buf的长度之后,问题找到了 长度 : 10

这就是说在进入到ByteToMessageDecoder这个解码器的时候,数据包已经只剩下10个长度了,那么长的数据被上个解码器DelimiterBasedFrameDecoder隔空劈开了- -。问题出现在哪呢,看上面那块字节流的字节,找到第11个字节,是0a。。。。因为不是标准的json格式,最前面使用了3个字节 加上2个int长度的属性,所以 数据包头应该是11个字节长。

而DelimiterBasedFrameDecoder在读到第11个字节的时候读成了n,自然而然的就认为这个数据包已经结束了,而数据进入到ByteToMessageDecoder的时候就会因为规定的body长度不等于length长度而出现问题。

思来想去 不实用n 这样的单字节作为换行符,很容易在数据流中遇到,转而使用rn俩字节来处理,而这俩字节出现在前面两个int长度中的几率应该很小。

最终解决

在客户端和服务器端的pipeline中添加 以 “rn” 定义为边界的符号来标识数据包结束

代码语言:javascript代码运行次数:0运行复制

//这里使用自定义分隔符ByteBuf delimiter = Unpooled.copiedBuffer("rn".getBytes());pipeline.addFirst(new DelimiterBasedFrameDecoder(8192, delimiter));

Server端

20-Netty TCP 粘包和拆包及解决方案

Client端

20-Netty TCP 粘包和拆包及解决方案

编码器中发送结束位置增加

代码语言:javascript代码运行次数:0运行复制

//这里最后修改使用rnout.writeBytes(new byte[]{'r','n'});
20-Netty TCP 粘包和拆包及解决方案

再次运行程序 数据包可以正常接收了。

最终测试

服务器端

代码语言:javascript代码运行次数:0运行复制

log4j:WARN No appenders could be found for logger (io.netty.util.internal.logging.InternalLoggerFactory).log4j:WARN Please initialize the log4j system properly.log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.server is ready ......服务器第1次接收到来自客户端的数据:今天天气冷, 打火锅0......服务器第999次接收到来自客户端的数据:今天天气冷, 打火锅998服务器第1000次接收到来自客户端的数据:今天天气冷, 打火锅999

客户端

代码语言:javascript代码运行次数:0运行复制

log4j:WARN No appenders could be found for logger (io.netty.util.internal.logging.InternalLoggerFactory).log4j:WARN Please initialize the log4j system properly.log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.客户端第1次接收服务端的回送:48fa6d78-8079-4700-b488-ca2af9eb3f8c......客户端第999次接收服务端的回送:581da47b-d77b-4972-af11-6d33057f6610客户端第1000次接收服务端的回送:0014e906-69cb-4900-9409-f4d1af9148dd

总结

以前使用netty的时候也仅限于和硬件交互,而当时的硬件受限于成本问题是一条一条处理数据包的,所以基本上不会考虑黏包问题

然后就是ByteToMessageDecoder和MessageToByteEncoder两个类是比较底层实现数据流处理的,并没有带有拆包黏包的处理机制,需要自己在数据包头规定包的长度,而且无法处理过大的数据包,因为我一开始首先使用了这种方式处理数据,所以后来就没有再换成DelimiterBasedFrameDecoder加 StringDecoder来解析数据包,最后使用json直接转化为对象。

FAQ 参考粘贴于大佬的博客,加自己的改动

以上就是20-Netty TCP 粘包和拆包及解决方案的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/813534.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
联发科宣布与 OPPO 合作共建轻量化大模型,强化生成式 AI 应用
上一篇 2025年11月26日 23:44:17
通过CMOS设置电脑定时自动开机
下一篇 2025年11月26日 23:44:21

相关推荐

  • 修复Django电商项目中AJAX过滤产品列表图片不显示问题

    在Django电商项目中,当使用AJAX动态加载过滤后的产品列表时,常遇到图片无法正常显示的问题。这通常是由于前端模板中图片加载方式(如data-setbg属性结合JavaScript库)与AJAX动态内容更新机制不兼容所致。解决方案是直接在AJAX返回的HTML中使用标准的标签来渲染图片,确保浏览…

    2026年5月10日
    000
  • Golang JSON序列化:控制敏感字段暴露的最佳实践

    本教程探讨golang中如何高效控制结构体字段在json序列化时的可见性。当需要将包含敏感信息的结构体数组转换为json响应时,通过利用`encoding/json`包提供的结构体标签,特别是`json:”-“`,可以轻松实现对特定字段的忽略,从而避免敏感数据泄露,确保api…

    2026年5月10日
    000
  • 怎么在PHP代码中实现图片上传功能_PHP图片上传功能实现与安全处理教程

    首先创建含enctype的HTML表单,再用PHP接收文件,检查目录、移动临时文件,验证类型与大小,生成唯一文件名,并调整php.ini限制以确保上传成功。 如果您尝试在PHP项目中添加图片上传功能,但服务器无法正确接收或保存文件,则可能是由于表单配置、文件处理逻辑或安全限制的问题。以下是实现该功能…

    2026年5月10日
    100
  • 比特币新手教程 比特币交易平台有哪些

    比特币是一种去中心化的数字货币,基于区块链技术实现点对点交易,具有匿名性、有限发行和不可篡改等特点;新手可通过交易所购买,P2P交易获得比特币,常用平台包括Binance、OKX和Huobi;交易流程包括注册账户、实名认证、绑定支付方式、充值法币并下单购买,可选择市价单或限价单;比特币存储方式有交易…

    2026年5月10日
    000
  • c++中的SFINAE技术是什么_c++模板编程中的SFINAE原理与应用

    SFINAE 是“替换失败不是错误”的原则,指模板实例化时若参数替换导致错误,只要存在其他合法候选,编译器不报错而是继续重载决议。它用于条件启用模板、类型检测等场景,如通过 decltype 或 enable_if 控制函数重载,实现类型特征判断。尽管 C++20 引入 Concepts 简化了部分…

    2026年5月10日
    000
  • HTML如何隐藏滚动条或去除滚动条

    滚动条可以存在也可以不存在,本文主要介绍了html 隐藏滚动条和去除滚动条的方法的相关资料,大家一起来学习一下html隐藏滚动条或去除滚动条的方法吧。 1. html 标签加属性 XML/HTML Code复制内容到剪贴板 2.body中加入以下代码 立即学习“前端免费学习笔记(深入)”; html…

    用户投稿 2026年5月10日
    000
  • Go语言mgo查询构建:深入理解bson.M与日期范围查询的正确实践

    本文旨在解决go语言mgo库中构建复杂查询时,特别是涉及嵌套`bson.m`和日期范围筛选的常见错误。我们将深入剖析`bson.m`的类型特性,解释为何直接索引`interface{}`会导致“invalid operation”错误,并提供一种推荐的、结构清晰的代码重构方案,以确保查询条件能够正确…

    2026年5月10日
    100
  • vscode上怎么运行html_vscode上运行html步骤【指南】

    首先保存文件为.html格式,再通过浏览器或Live Server插件打开预览;推荐安装Live Server实现本地服务器运行与实时刷新,提升开发体验。 在 VS Code 上运行 HTML 文件并不需要复杂的配置,只需几个简单步骤即可预览页面效果。VS Code 本身是一个代码编辑器,不直接运行…

    2026年5月10日
    100
  • 修复点击时按钮抖动:CSS垂直对齐实践

    本文探讨了在Web开发中,交互式按钮(如播放/暂停按钮)在点击时发生意外垂直位移的问题。通过分析CSS样式变化对元素布局的影响,我们发现这是由于按钮不同状态下的边框样式和内边距改变,以及默认的垂直对齐行为共同作用所致。核心解决方案是利用CSS的vertical-align属性,将其设置为middle…

    2026年5月10日
    000
  • Golang goroutine与channel调试技巧

    使用go run -race检测数据竞争,结合runtime.NumGoroutine监控协程数量,通过pprof分析阻塞调用栈,利用select超时避免永久阻塞,有效排查goroutine泄漏、死锁和数据竞争问题。 Go语言的goroutine和channel是并发编程的核心,但它们也带来了调试上…

    2026年5月10日
    000
  • 页面中文本域的值怎么设置

    标签定义多行的文本输入控件。 文本区中可容纳无限数量的文本,其中的文本的默认字体是等宽字体(通常是 Courier)。 可以通过 cols 和 rows 属性来规定 textarea 的尺寸,不过更好的办法是使用 CSS 的 height 和 width 属性。 注释:在文本输入区内的文本行间,用 …

    2026年5月10日
    000
  • 《魔兽世界》将于6月11日开启国服回归技术测试

    《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试

    《%ign%ignore_a_1%re_a_1%》官方宣布,将于6月11日开启国服回归技术测试,时间为7天,并称可以在6月内正式开服,玩家们可以访问官网下载战网客户端并预下载“巫妖王之怒”客户端,技术测试详情见下图。 WordAi WordAI是一个AI驱动的内容重写平台 53 查看详情 以上就是《…

    2026年5月10日 用户投稿
    200
  • 使用 Jupyter Notebook 进行探索性数据分析

    Jupyter Notebook通过单元格实现代码与Markdown结合,支持数据导入(pandas)、清洗(fillna)、探索(matplotlib/seaborn可视化)、统计分析(describe/corr)和特征工程,便于记录与分享分析过程。 Jupyter Notebook 是进行探索性…

    2026年5月10日
    000
  • 如何在HTML中插入表单元素_HTML表单控件与输入类型使用指南

    HTML表单通过标签构建,包含action和method属性定义数据提交目标与方式,常用input类型如text、password、email等适配不同输入需求,配合label、required、placeholder提升可用性,结合textarea、select、button等控件实现完整交互,是…

    2026年5月10日
    000
  • HTML5网页如何实现手势操作 HTML5网页移动端交互的处理技巧

    首先利用原生touch事件实现滑动判断,再通过preventDefault解决滚动冲突,接着引入Hammer.js处理复杂手势,最后通过优化点击区域、避免事件冲突和增加视觉反馈提升体验。 在移动端浏览器中,HTML5网页可以通过触摸事件实现手势操作,提升用户体验。虽然原生JavaScript提供了基…

    2026年5月10日
    000
  • 创建指定大小并填充特定数据的Golang文件教程

    本文将介绍如何使用Golang创建一个指定大小的文件,并用特定数据填充它。我们将使用 `os` 包提供的函数来创建和截断文件,从而实现快速生成大文件的目的。示例代码展示了如何创建一个10MB的文件,并将其填充为全零数据。掌握这些方法,可以方便地在例如日志系统或磁盘队列等场景中,预先创建测试文件或初始…

    2026年5月10日
    000
  • Python命令怎样使用profile分析脚本性能 Python命令性能分析的基础教程

    使用Python的cProfile模块分析脚本性能最直接的方式是通过命令行执行python -m cProfile your_script.py,它会输出每个函数的调用次数、总耗时、累积耗时等关键指标,帮助定位性能瓶颈;为进一步分析,可将结果保存为文件python -m cProfile -o ou…

    2026年5月10日
    000
  • 使用 WebCodecs VideoDecoder 实现精确逐帧回退

    本文档旨在解决在使用 WebCodecs VideoDecoder 进行视频解码时,实现精确逐帧回退的问题。通过比较帧的时间戳与目标帧的时间戳,可以避免渲染中间帧,从而提高用户体验。本文将提供详细的解决方案和示例代码,帮助开发者实现精确的视频帧控制。 在使用 WebCodecs VideoDecod…

    2026年5月10日
    000
  • 如何插入查询结果数据_SQL插入Select查询结果方法

    如何插入查询结果数据_SQL插入Select查询结果方法如何插入查询结果数据_SQL插入Select查询结果方法如何插入查询结果数据_SQL插入Select查询结果方法如何插入查询结果数据_SQL插入Select查询结果方法

    使用INSERT INTO…SELECT语句可高效插入数据,通过NOT EXISTS、LEFT JOIN、MERGE语句或唯一约束避免重复;表结构不一致时可通过别名、类型转换、默认值或计算字段处理;结合存储过程可提升可维护性,支持参数化与动态SQL。 将查询结果数据插入到另一个表中,可以…

    2026年5月10日 用户投稿
    000
  • PHP动态生成表单输入与POST数据获取实践指南

    本教程详细阐述了如何在php中根据动态数据源(如数据库值)生成多个表单输入框,并演示了如何通过post方法准确无误地获取这些动态生成的输入值。文章强调了正确的输入框命名策略,避免了常见的命名误区,并提供了完整的代码示例,确保开发者能够高效处理动态表单数据。 动态生成表单输入 在Web开发中,我们经常…

    2026年5月10日
    000

发表回复

登录后才能评论
关注微信