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,我會把你的文章引用放到頂上去