使用过Mina做Socket长链接的同学应该都遇到到过,在解码时少包、多包的问题!
1.文本内容发送端需要等缓冲区满才发送出去,造成粘包
2.接收方不及时接收缓冲区的包,造成多个包接收
解决方法就是使用CumulativeProtocolDecoder 解码器,确保在编码的时候要把前4位设成标志位,标志消息内容的长度。
数据包编码和解码一定要单独实现:
编码器 class RequestEncoder implements ProtocolEncoder
解码器 class RequestDecoder extends CumulativeProtocolDecoder
public class RequestDecoder extends CumulativeProtocolDecoder {
private String TAG = this.getClass().getName();
/**
* 返回值的解释:
* 1、false, 继续接收下一批数据,有两种情形,如缓冲区数据刚刚就是一个完整消息,或不够一条消息时。
* 如果不够一条消息,那么会将下一批数据和剩余消息进行合并
* 2、true, 当缓冲区的消息多于一条消息时,剩余消息会再会推送至doDecode
*/
protected boolean doDecode(IoSession session, IoBuffer in,
ProtocolDecoderOutput out) throws Exception {
if (in.remaining() < 4) {
in.reset();
return false;//继续接收数据,以待数据完整
}
in.mark();// 标记当前位置,以便reset
int size = in.getInt();// 读取4字节判断消息长度
if (in.remaining() < size) {// 如果消息内容不够,则重置,相当于不读取size
in.reset();
return false;// 接收新数据,以拼凑成完整数据
} else {
decodePacket(session, in, out, size);
}
if (in.remaining() > 0) {
in.mark();
return true;// 如果读取内容后还粘了包,就让父类再给俺 一次,进行下一次解析
} else {
return false;
}
}
private void decodePacket(IoSession session, IoBuffer in,
ProtocolDecoderOutput out, int size) {
try {
byte[] sizeBytes = new byte[size];
in.get(sizeBytes);
ResponseData data = ResponseData.parseFrom(sizeBytes);
Response response = new Response(data.getResId(),
data.getResCode(), data.getResData().toByteArray());
response.setSession(session);
response.setCallBack(data.getCallback());
Log.d(TAG, " >> " + response);
out.write(response);
} catch (Exception e) {
Log.d(TAG, "RequestEncoder encode:" + e);
}
}
}
public class RequestEncoder implements ProtocolEncoder {
private String TAG = this.getClass().getName();
@Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
Request request = (Request) message;
Log.d(TAG, " << " + request);
RequestData.Builder builder = RequestData.newBuilder();
if(request.getByteData() != null) {
builder.setByteData(ByteString.copyFrom(request.getByteData()));
}
builder.setReqData(request.getRequestData().toString());
builder.setReqId(request.getCommandId());
if (request.getCallBack() != null) {
builder.setCallback(request.getCallBack());
}
byte[] data = builder.build().toByteArray();
int dataLength = data.length;//int是4个字节32位
IoBuffer buffer = IoBuffer.allocate(4 + dataLength, false);//数据包长度信息+原始数据大小
buffer.putInt(dataLength);//先写入int大小的长度信息
buffer.put(data);//再写入要发送的请求数据
buffer.flip();
out.write(buffer);
buffer.free();
}
@Override
public void dispose(IoSession session) throws Exception {
}
}