mina框架虽然已经老了,不过还是比较常用的,遇到解码粘包问题时,就需要继承一个特定的解码器了——CumulativeProtocolDecoder。
顾名思义,这个解码器本身就是作为累积数据用的,为什么这么说呢?因为:
在deCode()方法返回false时,此解码器会把接收到的数据累积性地缓存至IoBuffer中。
这样只要继承此解码器,然后稍做处理,就可以摆脱粘包问题了。
比如,一次通信数据的格式为
type | len | content |
---|---|---|
int | int | String |
当我接收一次数据时,会首先通过得到len值来判断此次所有数据的长度,如果content的长度与len值相等,则此次数据接收完毕,否则将继续接收。
/**
* 数据通信解码--处理粘包
*/
public class UpdateDataDecoder extends CumulativeProtocolDecoder {
@Override
protected boolean doDecode(IoSession ioSession, IoBuffer ioBuffer, ProtocolDecoderOutput protocolDecoderOutput) throws Exception {
//标记位置,重置则从此处重置
ioBuffer.mark();
//报文类型
int type = ioBuffer.getInt();
//报文长度
int len = ioBuffer.getInt();
if (len > ioBuffer.remaining()) {
//若长度不够,则重置iobuffer,继续解析
ioBuffer.reset();
return false;
} else {
//否则视为解析完毕
String content1 = ioBuffer.getString(Charset.forName("utf-8").newDecoder());
protocolDecoderOutput.write(content1);
return true;
}
}
}
以上。