mina自定义IoFilter

bxqybxqy 2012-09-01

mina自定义编解码器
package wangmin.mina.server;

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

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class MyProtocolDecoder implements ProtocolDecoder{

	@Override
	public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
			throws Exception {
		TestMessage message = new TestMessage();
		message.setProtocolType(in.getShort());
		message.setMsgLength(in.getInt());
		Charset charset = Charset.forName("UTF-8");
		CharsetDecoder decoder = charset.newDecoder();
		String msgBody = in.getString(decoder);
		message.setMsgBody(msgBody);
		out.write(message);
	}

	@Override
	public void dispose(IoSession session) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void finishDecode(IoSession session, ProtocolDecoderOutput out)
			throws Exception {
		
	}

}
 
package wangmin.mina.server;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

public class MyProtocolEncoder implements ProtocolEncoder{

	@Override
	public void dispose(IoSession session) throws Exception {
		
	}

	@Override
	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws Exception {
		TestMessage msg = (TestMessage)message;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutput objout = new ObjectOutputStream(baos);
		objout.writeObject(msg);
		byte[] temp = baos.toByteArray();
		IoBuffer buffer = IoBuffer.wrap(temp);
		out.write(buffer);
	}

}

相关推荐

fengshantao / 0评论 2016-03-25

claytang / 0评论 2013-05-06