mina学习 粘包,断包处理

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;
	}
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值