根据文档封装解码消息

这篇我就留个记号,没什么意义,有些东西总是忘记,记一下好些。

package edcode;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.Arrays;
import java.util.List;

public class MyMessageDecoder extends ByteToMessageDecoder {
	public final int baselength=10;

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

		int length=in.readableBytes();
		byte[] msgByte = new byte[length];
		in.getBytes(in.readerIndex(),msgByte);//从byteBuff中可读位置开始,把in中的内容放入到msgByte字节数组中
		if(length<2){//如果消息体长度小于2,则什么都不做
			return;
		}
		byte[] headBytes = new byte[2];
		in.getBytes(in.readerIndex(),headBytes);//从指定的索引的位置开始,把此缓冲区的数据转移到指定的目标,即headBytes数组
		if(!"$$".equals(new String(headBytes))){//如果消息头不等于$$,则恢复缓冲区至初始状态
			in.clear();
			return;
		}
		int msgLen = in.getInt(in.readerIndex()+2);//此时可读的索引是0,加2就是从2开始,getint()的话,就往后读取4个字节,刚好对应平台分发协议文档的消息长度
		if(msgLen>length){
			return;
		}
//		String order = String.valueOf(in.getShort(in.readerIndex()+6));
		byte[] order = new byte[2];
		in.getBytes(in.readerIndex()+6,order);
		msgByte = new byte[msgLen];
		in.readBytes(msgByte);//把数据从缓冲区读取到指定的字节数组中,buffer(in)-->msgByte
		byte[] tailBytes= Arrays.copyOfRange(msgByte,msgByte.length-2,msgByte.length);
		if(!"##".equals(new String(tailBytes))){
			return;
		}
		byte[] body = Arrays.copyOfRange(msgByte,8,msgByte.length-2);
		MessageProtocal messageProtocal=new MessageProtocal();
		messageProtocal.setLen(msgLen);
		messageProtocal.setId(order);
		messageProtocal.setContent(body);
		out.add(messageProtocal);
	}

}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值