key words: netty 粘包 解包 半包 TCPapp
客户端发送消息tcp
String message = "netty is a nio server framework &" +"which enables quick and easy development &" +"of net applications such as protocol &" +"servers and clients!";
服务端添加解码器:DelimiterBasedFrameDecoder大数据
ByteBuf delimiter = Unpooled.copiedBuffer("&".getBytes()); ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter)); //1024表示单条消息的最大长度,解码器在查找分隔符的时候,达到该长度还没找到的话会抛异常 ch.pipeline().addLast(new StringDecoder()); .... ch.pipeline().addLast(new StringEncoder());
打印输出:ui
接收消息:[netty is a nio server framework ] 接收消息:[which enables quick and easy development ] 接收消息:[of net applications such as protocol] 接收消息:[servers and clients!]
参数解释:this
public DelimiterBasedFrameDecoder(int maxFrameLength, ByteBuf delimiter) { this(maxFrameLength, true, delimiter); } maxFrameLength:解码的帧的最大长度 stripDelimiter:解码时是否去掉分隔符 failFast:为true,当frame长度超过maxFrameLength时当即报TooLongFrameException异常,为false,读取完整个帧再报异常 delimiter:分隔符
参数说明:编码
服务端url
ch.pipeline().addLast(new FixedLengthFrameDecoder(30));//设置定长解码器 长度设置为30 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println("接收客户端msg:["+msg+"]"); ByteBuf echo=Unpooled.copiedBuffer(MESSAGE.getBytes()); ctx.writeAndFlush(echo); }
客户端netty
ch.pipeline().addLast(new FixedLengthFrameDecoder(30));//设置定长解码器
参数说明code
备注:若是长度解析失误,(过大,就直接丢弃这个包;太小,一、netty不抛出异常;二、校验通不过)server
源码: int frameLengthInt = (int) frameLength; if (in.readableBytes() < frameLengthInt) { return null; }
封包时配合使用LengthFieldPrepender,很容易加上包长度
在发布时,自动在帧的头部加上长度
参数说明:
lengthIncludesLengthFieldLength:false,长度字节不算在总长度中,true,算到总长度中
应用:
pipeline.addLast("frameEncode", new LengthFieldPrepender(4, false));
官方说明:
编码类,自动将 +----------------+ | "HELLO, WORLD" | +----------------+ 格式的数据转换成以下格式的数据, +--------+----------------+ + 0x000C | "HELLO, WORLD" | +--------+----------------+ 若是lengthIncludesLengthFieldLength设置为true,则编码为(多了两个字节) +--------+----------------+ + 0x000E | "HELLO, WORLD" | +--------+----------------+
当时解决问题和记录时,是查阅了官网和几篇博客,若是里面内容有copy的地方,请留言url,我会把你的文章引用放到顶上去