netty自定义协议解决粘包拆包问题

通过自定义 解码器来实现  不固定长度 固定帧头和帧尾的报文

 public  class FixedHeaderTailDecoder extends ByteToMessageDecoder {
              private static final short START_DELIMITER = (short) 0x4040;
              private static final short END_DELIMITER = (short) 0x2323;

              private enum State {
                  WAIT_START,
                  COLLECTING
              }

              private State currentState = State.WAIT_START;
              private int startIndex = -1;

              @Override
              protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
                  while (in.readableBytes() >= 2) {
                      switch (currentState) {
                          case WAIT_START:
                              if (in.getShort(in.readerIndex()) == START_DELIMITER) {
                                  startIndex = in.readerIndex();
                                  currentState = State.COLLECTING;
                              }
                              in.skipBytes(1);
                              break;

                          case COLLECTING:
                              if (in.getShort(in.readerIndex()) == END_DELIMITER) {
                                  int endIndex = in.readerIndex() + 2;
                                  int length = endIndex - startIndex;
                                  ByteBuf completeMessage = in.retainedSlice(startIndex, length);
                                  out.add(completeMessage);
                                  in.readerIndex(endIndex);
                                  currentState = State.WAIT_START;
                                  startIndex = -1;
                              } else {
                                  in.skipBytes(1);
                              }
                              break;
                      }
                  }
              }

              @Override
              protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
                  resetState();
                  super.handlerRemoved0(ctx);
              }
              @Override
              public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                  resetState();
                  ctx.fireExceptionCaught(cause);
              }
              private void resetState() {
                  currentState = State.WAIT_START;
                  startIndex = -1;
              }
          }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值