这篇我就留个记号,没什么意义,有些东西总是忘记,记一下好些。
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);
}
}