说明:
粘包:
现象:
发送abc、def,接收abcdef
原因:
- 应用层:接收方ByteBuf设置太大(Netty默认1024)
- 滑动窗口:假设发送方256 bytes示-个完整报文,但由于接收方处理不及时且窗口大小足够大,这256 bytes字节就会缓冲在接收方的滑动窗口中,当滑动窗口中缓冲了多个报文就会粘包
- Netty使用了Nagle算法将多次间隔较小且数据量小的数据合并成一个大的数据块进行封包发送
拆包(半包):
现象:
发送abcdef,接收abc、def
原因:
- 应用层:接收方ByteBuf小于实际发送数据量
- 滑动窗口:假设接收方的窗口只剩了128 bytes,发送方的报文大小是256 bytes,这时放不下了,只能先发送前128 bytes,等待ack后才能发送剩余部分,这就造成了半包
- MSS限制:当发送的数据超过MSS限制后会将数据切分发送,就会造成半包,本质是因为TCP是流式协议,消息无边界
假设客户端分别发送了两个数据包D1和D2给服务端,由于服务端一次读取到字节数是不确定的,故可能存在以下四种情况:
1、服务端分两次读取到了 两个独立的数据包,分别是D1和D2,没有粘包和拆包
2、服务端一次接受到了两个数据包,D1和D2粘合在一起,称之为TCP粘包
3、服务端分两次读取到了数据包,第一次读取到了完整的D1包和D2包的部分内容,第二次读取到了D2包的剩余内容,这称之为TCP拆包
4、服务端分两次读取到了数据包,第一次读取到了D1包的部分内容D1 1,第二次读取到了D1包的剩余部分内容D1 2和完整的D2,这称之为TCP拆包
拆包与粘包示意图
粘包拆包演示:
客户端向服务端循环发送数据,模拟出拆包粘包情况,源码地址
客户端:
package tcp;import io.netty.bootstrap.Bootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;public class MyTcpClient {public static void main(String[] args) throws Exception{EventLoopGroup group = new NioEventLoopGroup();try {Bootstrap bootstrap = new Bootstrap();bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast(new MyClientHandler());}});ChannelFuture channelFuture = bootstrap.connect("localhost", 7000).sync();channelFuture.channel().closeFuture().sync();}finally {group.shutdownGracefully();}}}
客户端Handler:
package tcp;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import io.netty.util.CharsetUtil;import java.util.concurrent.atomic.AtomicInteger;/* 自定义客户端Handler */public class MyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {private int sum;@Overrideprotected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {byte[] buffer = new byte[msg.readableBytes()];msg.readBytes(buffer);String message = new String(buffer, CharsetUtil.UTF_8);System.out.println("客户端接收到消息=" +message+" 当前次数:"+ (++this.sum) );}@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {//循环发送数据模拟粘包for (int i = 0; i < 10; ++i) {ByteBuf byteBuf = Unpooled.copiedBuffer("hello,server" + i, CharsetUtil.UTF_8);System.out.println("客户端发送消息,当前是第"+i+"次");ctx.writeAndFlush(byteBuf);}}/* 异常时触发 */@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {cause.printStackTrace();ctx.close();}}
服务端:
package tcp;import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioServerSocketChannel;public class MyTcpServer {public static void main(String[] args) throws Exception{EventLoopGroup bossGroup = new NioEventLoopGroup(1);EventLoopGroup workerGroup = new NioEventLoopGroup();try {ServerBootstrap serverBootstrap = new ServerBootstrap();serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast(new MyServerHandler());}});ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();channelFuture.channel().closeFuture().sync();}finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}}
服务端Handler:
package tcp;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import io.netty.util.CharsetUtil;import java.util.UUID;import java.util.concurrent.atomic.AtomicInteger;/* 自定义服务端Handler */public class MyServerHandler extends SimpleChannelInboundHandler<ByteBuf> {private int sum;@Overrideprotected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {byte[] buffer = new byte[msg.readableBytes()];msg.readBytes(buffer);String message = new String(buffer, CharsetUtil.UTF_8); //将buffer转成字符串System.out.println("服务器接收到数据: "+ message);System.out.println("服务器接收到消息量= " + (++this.sum) );//服务器返回数据给客户端ByteBuf responseBytebuf = Unpooled.copiedBuffer(UUID.randomUUID().toString(), CharsetUtil.UTF_8);ctx.writeAndFlush(responseBytebuf);}}
测试:
启动客户端与服务端,多次尝试后将出现粘包现象
粘包场景还原
解决方案:
使用 handler 时只有源码中声明了 @Sharable 才具有线程安全特性
解决方案 - 自定义协议包:
使用自定义协议 + 编解码器解决,核心在于确定服务端每次读取的数据长度,通过将数据封装到协议包来保证每次需要读取的数据内容,源码地址
自定义协议包:
package tcp.protocoltcp;import lombok.Getter;import lombok.Setter;import lombok.experimental.Accessors;/* 自定义协议包 */@Getter@Setter@Accessors(chain = true)public class MessageProtocol {private int len; //定义长度private byte[] content; //数据内容}
自定义编码器:
将需要发送的数据内容封装到协议包内在进行发送
package tcp.protocoltcp;import io.netty.buffer.ByteBuf;import io.netty.channel.ChannelHandlerContext;import io.netty.handler.codec.MessageToByteEncoder;/* 自定义协议包对应的编码器 */public class MyMessageEncoder extends MessageToByteEncoder<MessageProtocol> {@Overrideprotected void encode(ChannelHandlerContext ctx, MessageProtocol msg, ByteBuf out) throws Exception {System.out.println("自定义协议包对应编码器被调用");out.writeInt(msg.getLen());out.writeBytes(msg.getContent());}}
自定义解码器:
将协议包的数据进行解析
package tcp.protocoltcp;import io.netty.buffer.ByteBuf;import io.netty.channel.ChannelHandlerContext;import io.netty.handler.codec.ReplayingDecoder;import java.util.List;/* 自定义协议包对应的解码器 */public class MyMessageDecoder extends ReplayingDecoder<Void> {@Overrideprotected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {System.out.println("自定义协议包对应解码器被调用");//需要将得到的二进制字节码转为数据包int length = in.readInt();byte[] content = new byte[length];in.readBytes(content);MessageProtocol protocol = new MessageProtocol().setLen(length).setContent(content);out.add(protocol);}}
服务端Handler:
package tcp.protocoltcp;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import io.netty.util.CharsetUtil;/* 自定义客户端Handler */public class MyClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {private int sum;@Overrideprotected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {byte[] content = msg.getContent();int len = msg.getLen();String message = new String(content, CharsetUtil.UTF_8); //将buffer转成字符串System.out.println("客户端接收到服务器返回数据: "+ message+" 当前长度: "+len);System.out.println("客户端接收到消息量= " + (++this.sum) );}@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {//循环发送数据for (int i = 0; i < 5; ++i) {String msg = "当前是第" + i+"次签到";byte[] bytes = msg.getBytes(CharsetUtil.UTF_8);int length = msg.getBytes(CharsetUtil.UTF_8).length;//创建协议包对象MessageProtocol protocol = new MessageProtocol().setContent(bytes).setLen(length);System.out.println("客户端发送消息,当前是第"+i+"次");ctx.writeAndFlush(protocol);}}/* 异常时触发 */@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {cause.printStackTrace();ctx.close();}}
客户端Handler:
package tcp.protocoltcp;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import io.netty.util.CharsetUtil;import java.util.UUID;/* 自定义服务端Handler */public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {private int sum;@Overrideprotected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {byte[] content = msg.getContent();int len = msg.getLen();String message = new String(content, CharsetUtil.UTF_8); //将buffer转成字符串System.out.println("服务器接收到数据: "+ message+" 当前长度: "+len);System.out.println("服务器接收到消息量= " + (++this.sum) );//服务器返回数据给客户端String responseStr = UUID.randomUUID().toString();int length = responseStr.getBytes("utf-8").length;byte[] bytes = responseStr.getBytes();MessageProtocol protocol = new MessageProtocol().setLen(length).setContent(bytes);ctx.writeAndFlush(protocol);}}
客户端:
package tcp.protocoltcp;import io.netty.bootstrap.Bootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;/* 模拟出现Tcp粘包情况的客户端 */public class MyTcpClient {public static void main(String[] args) throws Exception{EventLoopGroup group = new NioEventLoopGroup();try {Bootstrap bootstrap = new Bootstrap();bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast(new MyMessageEncoder()); //自定义协议包对应的编码器pipeline.addLast(new MyMessageDecoder()); //自定义协议包对应的解码器pipeline.addLast(new MyClientHandler());}});ChannelFuture channelFuture = bootstrap.connect("localhost", 7000).sync();channelFuture.channel().closeFuture().sync();}finally {group.shutdownGracefully();}}}
服务端:
package tcp.protocoltcp;import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioServerSocketChannel;/* 模拟出现Tcp粘包情况的服务端 */public class MyTcpServer {public static void main(String[] args) throws Exception{EventLoopGroup bossGroup = new NioEventLoopGroup(1);EventLoopGroup workerGroup = new NioEventLoopGroup();try {ServerBootstrap serverBootstrap = new ServerBootstrap();serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast(new MyMessageDecoder()); //自定义协议包的解码器pipeline.addLast(new MyMessageEncoder()); //自定义协议包的编码器pipeline.addLast(new MyServerHandler());}});ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();channelFuture.channel().closeFuture().sync();}finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}}
测试:
启动服务端和客户端,消息将先通过协议包到达编码器和解码器,每次都只会读取协议包内的数据来实现粘包&拆包问题的解决
拆包粘包问题得到解决
解决方案 - 定长解码器:
使用定长解码器FixedLengthFrameDecoder对完整数据包的长度进行指定,只有符合长度时才会被获取到,不符合长度则会等待下一次数据包进行数据拼接,有线程安全问题,源码地址
定长解码器源码中的注释
服务端:
package tcp.fixedlengthframe;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 io.netty.handler.codec.FixedLengthFrameDecoder;import io.netty.util.CharsetUtil;import java.nio.charset.StandardCharsets;import java.util.UUID;/* 使用定长解码器解决拆包粘包问题 - 服务端 */public class MyTcpServer2 {public static void main(String[] args) throws Exception{EventLoopGroup bossGroup = new NioEventLoopGroup(1);EventLoopGroup workerGroup = new NioEventLoopGroup();try {ServerBootstrap serverBootstrap = new ServerBootstrap();serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast(new FixedLengthFrameDecoder(13)); //添加定长解码器,指定数据长度为10pipeline.addLast(new SimpleChannelInboundHandler<ByteBuf>() {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {String message = msg.toString(CharsetUtil.UTF_8);System.out.println("服务器接收到数据: "+ message);}});}});ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();channelFuture.channel().closeFuture().sync();}finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}}
客户端:
package tcp.fixedlengthframe;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 io.netty.util.CharsetUtil;import java.nio.charset.StandardCharsets;/* 使用定长解码器解决拆包粘包问题 - 客户端 */public class MyTcpClient2 {public static void main(String[] args) throws Exception{EventLoopGroup group = new NioEventLoopGroup();try {Bootstrap bootstrap = new Bootstrap();bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast(new ChannelInboundHandlerAdapter(){@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {//循环发送数据模拟粘包for (int i = 0; i < 10; ++i) {ByteBuf buffer = ctx.alloc().buffer();buffer.writeBytes(("hello,server"+i).getBytes(StandardCharsets.UTF_8));ctx.writeAndFlush(buffer);}}});}});ChannelFuture channelFuture = bootstrap.connect("localhost", 7000).sync();channelFuture.channel().closeFuture().sync();}finally {group.shutdownGracefully();}}}
测试:
定长解码器将数据包进行长度分割,成功获取数据
解决方案 - 分隔符解码器:
使用分隔符解码器LineBasedFrameDecoder对数据包的长度进行分割,每个数据末尾需要有分割符,实际开发中较为少用,有线程安全问题,源码地址
分隔符解码器源码使用介绍
服务端:
package tcp.linebaseframe;import io.netty.bootstrap.ServerBootstrap;import io.netty.buffer.ByteBuf;import io.netty.channel.*;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioServerSocketChannel;import io.netty.handler.codec.FixedLengthFrameDecoder;import io.netty.handler.codec.LineBasedFrameDecoder;import io.netty.util.CharsetUtil;/* 使用分隔符解码器解决拆包粘包问题 - 服务端 */public class MyTcpServer3 {public static void main(String[] args) throws Exception{EventLoopGroup bossGroup = new NioEventLoopGroup(1);EventLoopGroup workerGroup = new NioEventLoopGroup();try {ServerBootstrap serverBootstrap = new ServerBootstrap();serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast(new LineBasedFrameDecoder(1024)); //添加分隔符解码器,需要设置数据包最大长度pipeline.addLast(new SimpleChannelInboundHandler<ByteBuf>() {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {String message = msg.toString(CharsetUtil.UTF_8);System.out.println("服务器接收到数据: "+ message);}});}});ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();channelFuture.channel().closeFuture().sync();}finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}}
客户端:
package tcp.linebaseframe;import io.netty.bootstrap.Bootstrap;import io.netty.buffer.ByteBuf;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 MyTcpClient3 {public static void main(String[] args) throws Exception{EventLoopGroup group = new NioEventLoopGroup();try {Bootstrap bootstrap = new Bootstrap();bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast(new ChannelInboundHandlerAdapter(){@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {//循环发送数据,末尾需要使用分隔符,这样服务端分隔符解码器才能正确识别for (int i = 0; i < 10; ++i) {ByteBuf buffer = ctx.alloc().buffer();buffer.writeBytes(("hello,server"+i+"\n").getBytes(StandardCharsets.UTF_8));ctx.writeAndFlush(buffer);}}});}});ChannelFuture channelFuture = bootstrap.connect("localhost", 7000).sync();channelFuture.channel().closeFuture().sync();}finally {group.shutdownGracefully();}}}
测试:
分隔符解码器根据分隔符对数据包进行分割,成功获取数据
解决方案 - 长度分割解码器:
使用长度分割解码器 LengthFieldBasedFrameDecoder 对数据包进行切割,可以拆出数据包内的指定索引位的数据,有线程安全问题,源码地址
主要参数如下所示:
| 参数名 | 含义 |
|---|---|
| maxFrameLength | 单个数据包最大长度 |
| lengthFieldOffset | 长度字段起始索引位 |
| lengthFieldLength | 长度字段长度(16进制长度) |
| lengthAdjustment | 从长度字段结束后开始算,还有几个字节才是内容 |
| initialBytesToStrip | 接收数据是从头部开始的几个字节是不需要的 |
客户端:
package tcp.lengthfieldbasedframe;import io.netty.bootstrap.Bootstrap;import io.netty.buffer.ByteBuf;import io.netty.buffer.ByteBufAllocator;import io.netty.channel.*;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;import io.netty.util.CharsetUtil;import java.nio.charset.StandardCharsets;import static io.netty.buffer.ByteBufUtil.appendPrettyHexDump;import static io.netty.util.internal.StringUtil.NEWLINE;/* 使用 解码器解决拆包粘包问题 - 客户端 */public class MyTcpClient4 {public static void main(String[] args) throws Exception{EventLoopGroup group = new NioEventLoopGroup();try {Bootstrap bootstrap = new Bootstrap();bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast(new ChannelInboundHandlerAdapter(){@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {//循环发送数据for (int i = 0; i < 10; ++i) {ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();String info = "hello,server";byte[] infoBytes = info.getBytes(CharsetUtil.UTF_8);buffer.writeInt(infoBytes.length); //写入数据长度,是不需要的信息,将会转换为16进制进行储存,因此服务端截取应该是从4开始buffer.writeBytes(infoBytes); //写入内容Log(buffer);ctx.writeAndFlush(buffer);}}});}});ChannelFuture channelFuture = bootstrap.connect("localhost", 7000).sync();channelFuture.channel().closeFuture().sync();}finally {group.shutdownGracefully();}}private static void Log(ByteBuf buffer) {int Length = buffer.readableBytes();int rows = Length / 16 + (Length % 15 == 0 ? 0 : 1) + 4;StringBuilder buf =new StringBuilder(rows * 80 * 2).append("read index:").append(buffer.readerIndex()).append(" write index: ").append(buffer.writerIndex()).append(" capacity:").append(buffer.capacity()).append(NEWLINE);appendPrettyHexDump(buf, buffer);System.out.println(buf.toString());}}
服务端:
客户端写入数据转为Byte字节后,前4位为writeInt方法写入的有效数据长度,且接收时数据包的长度位是不需要的,因此 initialBytesToStrip 值为 4,lengthFieldOffset 值为 0,lengthFieldLength 值为 4,长度字段和目标数据字段中间没有其他字段,因此 lengthAdjustment 值为 0
package tcp.lengthfieldbasedframe;import io.netty.bootstrap.ServerBootstrap;import io.netty.buffer.ByteBuf;import io.netty.channel.*;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioServerSocketChannel;import io.netty.handler.codec.LengthFieldBasedFrameDecoder;import io.netty.handler.codec.LineBasedFrameDecoder;import io.netty.handler.codec.string.StringDecoder;import io.netty.handler.codec.string.StringEncoder;import io.netty.util.CharsetUtil;import lombok.extern.java.Log;import static io.netty.buffer.ByteBufUtil.appendPrettyHexDump;import static io.netty.util.internal.StringUtil.NEWLINE;/* 使用 解码器解决拆包粘包问题 - 服务端 */public class MyTcpServer4 {public static void main(String[] args) throws Exception{EventLoopGroup bossGroup = new NioEventLoopGroup(1);EventLoopGroup workerGroup = new NioEventLoopGroup();try {ServerBootstrap serverBootstrap = new ServerBootstrap();serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast(new LengthFieldBasedFrameDecoder(1024,0,4,0,4)); //添加分隔符解码器,需要设置数据包最大长度pipeline.addLast(new SimpleChannelInboundHandler<ByteBuf>() {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {Log(msg);String message = msg.toString(CharsetUtil.UTF_8);System.out.println("服务器接收到数据: "+ message);}});}});ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();channelFuture.channel().closeFuture().sync();}finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}private static void Log(ByteBuf buffer) {int Length = buffer.readableBytes();int rows = Length / 16 + (Length % 15 == 0 ? 0 : 1) + 4;StringBuilder buf =new StringBuilder(rows * 80 * 2).append("read index:").append(buffer.readerIndex()).append(" write index: ").append(buffer.writerIndex()).append(" capacity:").append(buffer.capacity()).append(NEWLINE);appendPrettyHexDump(buf, buffer);System.out.println(buf.toString());}}
测试:
运行结果可查看具体字节截取效果
