mina框架分析:自定义编码解码

mina支持自定义编码和解码,要完成自定义的,简单来讲需要完成三部分:

1)实现自己的编码器,继承与ProtocolEncoderAdapter;

package org.mina.server.codec;

import java.nio.charset.Charset;

import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

/**
 * 编码器,用于发送数据时打包
 * */
public class MyEncoder extends ProtocolEncoderAdapter {

	private final Charset charset;

	static Logger log = Logger.getRootLogger();

	public MyEncoder(Charset charset) {
		this.charset = charset;
	}

	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws Exception {
		log.debug("MyEncoder.encode()");
		
		//......实现编码..........//
	}
	
}


2)实现自己的解码器  ,继承与ProtocolDecoderAdapter


package org.mina.server.codec;

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.AttributeKey;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderAdapter;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

/**
 * 解码器,用于接收数据时解码
 * */
public class MyDecoder extends ProtocolDecoderAdapter {

	static Logger log = Logger.getRootLogger();

	private final Charset charset;

	public MyDecoder() {
		this(Charset.defaultCharset());
	}

	public MyDecoder(Charset charset) {
		this.charset = charset;
	}

	public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
			throws Exception {
		log.debug("MyDecoder.decode()");

		//....接受数据,完成解码工作
		

	}

	public void dispose(IoSession session) throws Exception {
		log.debug("MyDecoder.dispose()");
	}

}


3)新建一个编/解码工厂,继承与ProtocolCodecFactory

package org.mina.server.codec;

import java.nio.charset.Charset;

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 MsgCodecFactory implements ProtocolCodecFactory {
	
	private final MsgEncoder encoder;
	private final MsgDecoder decoder;
	
	public MsgCodecFactory(){
		this(Charset.defaultCharset());
	}
	
	public MsgCodecFactory(Charset charset){
		this.encoder = new MsgEncoder(charset);
		this.decoder = new MsgDecoder(charset);
	}

	public ProtocolDecoder getDecoder(IoSession session) throws Exception {
		return decoder;
	}

	public ProtocolEncoder getEncoder(IoSession session) throws Exception {
		return encoder;
	}

}

完成了这三部分,那么在我们使用的时候,只需要在开始业务处理的地方直接使用。

DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();

chain.addLast("decoderFilter", new ProtocolCodecFilter(new MyCodecFactory(Charset.forName("UTF-8"))));

网上这类的帖子很少,好桑心~

参考:http://item.congci.com/item/apache-mina-zidingyi-bianjiema

你可能感兴趣的:(java编程)