/**
* 一、netty本身提供了四种不同的解码器供用户使用,但并不能完全满足所有需求,这时就需要自定义解码器用于netty加载得到我们想要的数据。
* demo是将tcp的流信息进行截取,ConstantValue.START_DATA = 0x40,ConstantValue.END_DATA = 0x23;
* 截取为例如:十六进制 40 40 。。。。23 23 的数据包,用于实际应用或存储。
* 代码如下:
*/
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer,
Listout) throws Exception {
int beginReader = 0;
while(buffer.isReadable()) {
beginReader = buffer.readerIndex();
buffer.markReaderIndex();
buffer.resetReaderIndex();
buffer.readByte();
if(beginReader >= 0){
if (((buffer.getByte(0) == ConstantValue.START_DATA))) {
if(beginReader >= 1) {
if (!((buffer.getByte(1) == ConstantValue.START_DATA))) {//如果第二位不是40,丢弃
buffer.discardReadBytes();
continue;
}
}
} else {
buffer.discardReadBytes();
continue;
}
}
if(beginReader > 2){
if (!((buffer.getByte(beginReader) == ConstantValue.END_DATA) && (buffer.getByte(beginReader -1) == ConstantValue.END_DATA))) {
continue;
} else {
int length = buffer.readerIndex();
byte[] data = new byte[length];
for(int i = 0; i < length; i++){
data[i] = buffer.getByte(i);
}
SmartCarProtocol protocol = new SmartCarProtocol(data.length, data);
out.add(protocol);
buffer.discardReadBytes();
break;
}
}
}
if (!((buffer.getByte(beginReader) == ConstantValue.END_DATA) && (buffer.getByte(beginReader -1) == ConstantValue.END_DATA))) {
buffer.readerIndex(beginReader); //收不到2323则返回继续
return;
}
}
// 对象类,用于存储数据
SmartCarProtocol
public class SmartCarProtocol {
private int head_data = ConstantValue.HEAD_DATA;
private int contentLength;
private byte[] content;
public SmartCarProtocol(int contentLength, byte[] content) {
this.contentLength = contentLength;
this.content = content;
}
public int getHead_data() {
return head_data;
}
public int getContentLength() {
return contentLength;
}
public void setContentLength(int contentLength) {
this.contentLength = contentLength;
}
public byte[] getContent() {
return content;
}
public void setContent(byte[] content) {
this.content = content;
}
@Override
public String toString() {
return "SmartCarProtocol [head_data=" + head_data + ", contentLength="
+ contentLength + ", content=" + Arrays.toString(content);
}