关于netty:netty自定义解码器

25次阅读

共计 1882 个字符,预计需要花费 5 分钟才能阅读完成。

/**

     * 一、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);  
}  

正文完
 0