您的位置:首页 > 其它

mina学习 粘包,断包处理

2013-08-02 14:06 211 查看
1.可以在过滤器中添加协议添加协议
acceptor.getFilterChain().addLast("protocol", new ProtocolCodecFilter(new CodecFactory()));

在CodecFactory中处理

import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolEncoder;

public class CodecFactory implements ProtocolCodecFactory {
private ProtocolEncoder encoder;
private ProtocolDecoder decoder;

public CodecFactory() {
this.encoder = new ResponseEncoder();
this.decoder = new RequestDecoder();
}

public ProtocolEncoder getEncoder(IoSession ioSession) throws Exception {
return this.encoder;
}

public ProtocolDecoder getDecoder(IoSession ioSession) throws Exception {
return this.decoder;
}
}


package com.epdc.socket.server.protocol;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class RequestDecoder extends CumulativeProtocolDecoder {
private final static Log LOG = LogFactory.getLog(RequestDecoder.class);

protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
if (in.remaining() > 0) {// 有数据时,读取2字节判断消息长度
byte[] sizeBytes = new byte[2];
in.mark();// 标记当前位置,以便reset
in.get(sizeBytes);// 读取前2字节
int size = Integer.valueOf(HexUtil.bytes2hex(sizeBytes), 16);
// 如果消息内容的长度不够则直接返回true
if (size > in.remaining()) {// 如果消息内容不够,则重置,相当于不读取size
in.reset();
LOG.debug("消息内容不够 断包了");
return false;// 接收新数据,以拼凑成完整数据
} else {
byte[] bytes = new byte[size];
in.get(bytes, 0, size);
RequestModel model= new RequestModel(sizeBytes, bytes);
out.write(model);
if (in.remaining() > 0) {// 如果读取内容后还粘了包,就让父类再一次进行下一次解析
LOG.debug("读取内容粘包了");
return true;
}
}
}
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: