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()));