apache mina 自定义编码解码

mina允许自定义数据传输的编码和解码方式

需要
实现ProtocolCodecFactory接口的工厂类
实现ProtocolDecoder接口的解码类
实现ProtocolEncoder接口的编码类

本例以client和server端都是java实现

首先定义传输的数据格式:
编码和解码都是针对数据字节。
数据格式:A+B+C+D
A:固定长度 6个字节,用来简单表示时间戳,
  月日年,时分秒每个一字节,年取后两位
B:内容(C+D)的length,固定长度,4个字节
C:请求指令:固定长度,4个字节
D:传递内容:不固定,json格式

这样针对上面的数据结构定义一个bean

public class MyMessage implements Serializable {
	
	/****/
	private static final long serialVersionUID = 5570201892267872279L;
	private Date date;//时间
	private int command;//指令
	private byte[] contents;//内容
	public int getCommand() {
		return command;
	}
	public void setCommand(int command) {
		this.command = command;
	}
	public byte[] getContents() {
		return contents;
	}
	public void setContents(byte[] contents) {
		this.contents = contents;
	}
	
	public int length(){
		return contents.length;
	}
	public Date getDate() {
		return date;
	}
	public void setDate(Date date) {
		this.date = date;
	}
}


编码类,继承org.apache.mina.filter.codec.CumulativeProtocolDecoder
重新encode方法即可

public class MyEncoder implements ProtocolEncoder {
	@Override
	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws Exception {
		MyMessage msg = (MyMessage) message;
		IoBuffer buffer = IoBuffer.allocate(1024);
		buffer.setAutoExpand(true);
		//编码数据结构的A,时间戳
		buffer.put(getTimeTag(msg.getDate()));
		//数据结构的B
		buffer.putInt(msg.length()+4);
		//数据结构的C
		buffer.putInt(msg.getCommand());
		//数据结构的D
		buffer.put(msg.getContents());
		buffer.flip();
		
		out.write(buffer);
	}

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

	public static byte[] getTimeTag(Date date){
		if(date == null){
			date = new Date();
		}
		Calendar c = Calendar.getInstance();
		c.get(Calendar.YEAR);
		String dateStr = sdf.format(date);
		String[] dates = dateStr.split("-");
		byte[] bt = new byte[dates.length];
		for(int a=0;a<dates.length;a++){
			bt[a] = Byte.parseByte(dates[a]);
		}
		return bt;
	}
}

解码类,继承自org.apache.mina.filter.codec.CumulativeProtocolDecoder
重新decode方法

public class MyDecoder extends CumulativeProtocolDecoder {

	@Override
	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {
			//读取数据结构A
			byte[] dateTag = new byte[6];
			in.get(dateTag);
			//读取数据结构B
			int length =in.getInt();
			//读取数据结构C
			int command = in.getInt();
			//读取数据结构D
			byte[] bytes = new byte[length-4];
			in.get(bytes);
			//提取出数据结构对象
			MyMessage msg = new MyMessage();
			msg.setCommand(command);
			msg.setContents(bytes);
			out.write(msg);
			return true;
	}
}


工厂类,很简单。主要是给server端和client端提供使用
public class MyCodeFactory implements ProtocolCodecFactory{
	
	private ProtocolDecoder decoder;
	private ProtocolEncoder encoder;
	
	public MyCodeFactory() {
		decoder = new MyDecoder();
		encoder = new MyEncoder();
	}

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

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


写到这里基本上自定义编码解码部分就完成了,下面使用就和其他已有mina提供的
编码解码filter一样使用了

首先还是要定义两个handler

server端handler:

public class MyServerHandler extends IoHandlerAdapter {
	   @Override
	    public void exceptionCaught( IoSession session, Throwable cause ) throws Exception
	    {
	        cause.printStackTrace();
	        session.close(true);
	    }
	    @Override
	    public void messageReceived( IoSession session, Object message ) throws Exception
	    {	
	     //收到了上面解码后的消息
	    	MyMessage msg = (MyMessage) message;
	    	if(message == null){
	    		//TODO 
	    	}
	    		
	    	int cmd = msg.getCommand();
	    	String body = new String(msg.getContents());
	    	String result = "";
		//TODO
		/**
		  根据请求指令的不同,调用后续的业务,
		  然后响应内容到client
		*/
	    	System.out.println(msg.getCommand()+"-----"+new String(msg.getContents()));
	        session.write(msg);
	    }
}


client端handler

public class MyClientHandler extends IoHandlerAdapter {
	@Override
	public void sessionOpened(IoSession session) throws Exception {
		//session.write(obj);
	}
	
	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
			//收到消息,。。。
		MyMessage gm = (MyMessage) message;
		System.out.println(gm.getCommand()+":"+new String(gm.getContents()));
	}
	
	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		session.close(true);
	}
}


server端配置:

	IoAcceptor accepter = new NioSocketAcceptor();
	ProtocolCodecFilter coderFilter = 
	//使用自定义的编码解码filter
	  new ProtocolCodecFilter(new MyCodeFactory());
	accepter.getFilterChain().addLast("a", new LoggingFilter());
	accepter.getFilterChain().addLast("b",coderFilter);
	//绑定handler
	accepter.setHandler(new MyServerHandler());
	
	accepter.getSessionConfig().setReadBufferSize(2048);
	accepter.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
	accepter.bind(new InetSocketAddress(8484));

client端配置:

		NioSocketConnector connector = new NioSocketConnector();
		connector.setConnectTimeoutMillis(20000);
		connector.getFilterChain().addLast("codes", new ProtocolCodecFilter(
				new MyCodeFactory()));
		connector.setHandler(new MyClientHandler());
		ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 8484));
		future.awaitUninterruptibly();
		IoSession session = null;
		session = future.getSession();
		
		MyMessage gm = new MyMessage();
		Map<String, String> map = new HashMap<String, String>();
		gm.setCommand(101);
		map.put("name", "bird");
		map.put("age", "7");
		//JsonUtil json工具类,map转json,随便找个就行
		gm.setContents(JsonUtil.objectToStr(map).getBytes());
		session.write(gm);
		
		connector.dispose();


运行后server端会打印:1001-----{"name":"c","age":"7"}
client:1001:{"name":"c","age":"7"}

都能正确获取到传递的内容。

猜你喜欢

转载自nullpoint.iteye.com/blog/2042206
今日推荐