netty自定义解码器

在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 }

 

转载于:https://www.cnblogs.com/huzi007/p/11334178.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值