编解码工厂。因为网络通讯过程中用的协议不一样,不同协议的消息格式不同,所以需要有编解码器实现字节流到具体消息对象的转换。通常在解码过程中如果出现解码错误,说明消息在传递过程中可能存在丢失或更改的情况,这时需要将与客户端的会话关闭。
package minabase.server;
import org.apache.mina.filter.codec.demux.DemuxingProtocolCodecFactory;
import org.apache.mina.filter.codec.demux.MessageDecoder;
import org.apache.mina.filter.codec.demux.MessageEncoder;
/**
* Class Description: 编解码工厂
* Copyright: Copyright (c)
*
*/
public class MyCodecFactory extends DemuxingProtocolCodecFactory
{
private MessageDecoder decoder;
private MessageEncoder<String> encoder;
// 注册编解码器
public MyCodecFactory(MessageDecoder decoder, MessageEncoder<String> encoder)
{
this.decoder = decoder;
this.encoder = encoder;
addMessageDecoder(this.decoder);
addMessageEncoder(String.class, this.encoder);
}
}
编码器
package minabase.server;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.filter.codec.demux.MessageEncoder;
/**
* Class Description: 编码器,在每个消息后面加\n
* Copyright: Copyright (c)
*
*/
public class MyCodecEncoder implements MessageEncoder<String>
{
private CharsetEncoder cecoder;
public MyCodecEncoder(Charset charset)
{
cecoder = charset.newEncoder();
}
@Override
public void encode(IoSession session, String in, ProtocolEncoderOutput out)
throws Exception
{
IoBuffer buf = IoBuffer.allocate(100).setAutoExpand(true);
String strMsg = in.toString();
try
{
buf.putString(strMsg, cecoder);
buf.put((byte)'\n');
}
catch (CharacterCodingException e)
{
//log
}
buf.flip();
out.write(buf);
}
}