在socket傳輸通信中容易丟包問題,什么半包問題,這些都是很正常的問題,處理方法就是定義自己的編解碼規則了,讓每次接收按定義好的規則為一個完整包作為數據源即可。
下面個例子就是netty自定義的一個解碼器:
1 import io.netty.buffer.ByteBuf; 2 import io.netty.buffer.ByteBufAllocator; 3 import io.netty.channel.ChannelHandlerContext; 4 import io.netty.handler.codec.ByteToMessageDecoder; 5 import java.util.List; 6 7 public class XmlDecoder extends ByteToMessageDecoder { 8 9 String lastStr = ""; 10 11 @Override 12 protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { 13 System.out.println("解碼器:"); 14 int len = in.readableBytes(); 15 if (len < 1) return; 16 byte[] bytes = new byte[len]; 17 in.getBytes(0, bytes); 18 String temp = new String(bytes); 19 //這里為XML結束標簽,自行替換 20 int index = temp.indexOf("</body>"); 21 if (index == -1) { 22 lastStr += temp; 23 } else { 24 lastStr += temp.substring(0, index+14 ); 25 ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(); 26 buffer.writeBytes(lastStr.getBytes()); 27 out.add(buffer); 28 lastStr = ""; 29 } 30 in.skipBytes(len); 31 } 32 33 }