Mina 解码器

1.定义Decode

package test.mina;

import java.util.Arrays;

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 MessageDecoder extends CumulativeProtocolDecoder {

	@Override
	public boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
		try {
//可以使用这两个函数,比较整数后面的长度大于等于prefixLength转换为整数后的长度
//in.prefixedDataAvailable(prefixLength)
//in.prefixedDataAvailable(prefixLength, maxDataLength)
			if (in != null && in.remaining() >= 4) {
				in.mark();
				byte[] b = new byte[4];
				in.get(b);
				int length = ByteUtil.byte2int(b, 0);
				in.reset();
				if (in.remaining() >= length) {
					byte[] bytes = new byte[length];
					in.get(bytes);
					out.write(IoBuffer.wrap(bytes));
					return true;
				}
			}
		} catch (Exception e) {

		return false;

	}

}

 

2.定义Encode

package test.mina;

import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

public class MessageEncoder extends ProtocolEncoderAdapter {

	@Override
	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws Exception {

	}

}

 

3.定义Factory

package test.mina;

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 Log log = LogFactory.getLog(this.getClass().getName());

	private final MessageDecoder decoder;
	private final MessageEncoder encode;

	public CodecFactory() {
		decoder = new MessageDecoder();
		encode = new MessageEncoder();
	}

	@Override
	public ProtocolEncoder getEncoder(IoSession session) throws Exception {

		return encode;
	}

	@Override
	public ProtocolDecoder getDecoder(IoSession session) throws Exception {

		return decoder;
	}

}

4.加入客户端或服务器

//Client 注意顺序
connector.getFilterChain().addLast("codec",
				new ProtocolCodecFilter(new CodecFactory()));

connector.getFilterChain().addLast("threadPool-client",
				new ExecutorFilter(executor));


//Server
acceptor.getFilterChain().addLast("codec",
					new ProtocolCodecFilter(new CodecFactory()));

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值