package com.example.mina.client.base; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.*; public class ByteProtocolFactory implements ProtocolCodecFactory { private final ByteEncoder encoder; private final ByteDecoder decoder; //构造 public ByteProtocolFactory() { encoder = new ByteEncoder(); decoder = new ByteDecoder(); } @Override public ProtocolDecoder getDecoder(IoSession arg0) throws Exception { return decoder; } @Override public ProtocolEncoder getEncoder(IoSession arg0) throws Exception { return encoder; } public class ByteEncoder extends ProtocolEncoderAdapter { //编码 将数据包转成字节数组 @Override public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception { byte[] bytes = (byte[]) message; IoBuffer buffer = IoBuffer.allocate(bytes.length); buffer.setAutoExpand(true); // 将数据放入缓冲IoBuffer buffer.put(bytes); // 写状态切换到读状态 buffer.flip(); out.write(buffer); } } public class ByteDecoder extends ProtocolDecoderAdapter { @Override public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { int limit = in.limit(); byte[] bytes = new byte[limit]; in.get(bytes); out.write(bytes); } } }