码迷,mamicode.com
首页 > Web开发 > 详细

apache mina:实现固定字节长度编码解码

时间:2016-05-07 09:29:01      阅读:381      评论:0      收藏:0      [点我收藏+]

标签:


在apache  mina 中存在一些解码器。

单字节解码器SingleByteDecodingState

短整型解码器ShortIntegerDecodingState

整型解码器IntegerDecodingState

固定长度字节解码器FixedLengthDecodingState


服务器端代码:

public class TestServer
{
	public static void main(String[] args) throws IOException
	{
		IoAcceptor acceptor = new NioSocketAcceptor();
		acceptor.getFilterChain().addLast("logger", new LoggingFilter());
		acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new FixedLengthEncoder(),new FixedLengthDecoder()));
		acceptor.setHandler(new FixedLengthIoHandlerAdapter());
		acceptor.bind(new InetSocketAddress(9999));
	}
}

客户端代码:

public class TestClient
{
	public static void main(String[] args)
	{
		NioSocketConnector connector = new NioSocketConnector();
		connector.setConnectTimeoutMillis(10000);

		connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new FixedLengthEncoder(),new FixedLengthDecoder()));

		connector.getFilterChain().addLast("logger", new LoggingFilter());
        connector.setHandler(new FixedLengthIoHandlerAdapter());
		IoSession session;

		for (;;)
		{
			try
			{
				ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 9999));
				future.awaitUninterruptibly();
				session = future.getSession();
				break;
			}
			catch (RuntimeIoException e)
			{

				e.printStackTrace();
				try
				{
					Thread.sleep(5000);
				}
				catch (InterruptedException e1)
				{
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}
        for (int i = 0; i < 10; i++)
		{
			session.write(i);
		}
		// wait until the summation is done
		session.getCloseFuture().awaitUninterruptibly();
		connector.dispose();
	}
}

固定字节长度解码器:

public class FixedLengthDecoder extends CumulativeProtocolDecoder
{

	private static final String PREFIX_DECODINGSTATE = "PREFIX_DECODINGSTATE";

	@Override
	protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception
	{
		FixedLengthDecodingStateImpl state = (FixedLengthDecodingStateImpl)session.getAttribute(PREFIX_DECODINGSTATE);
        if(state ==null)
        {
        	state =new FixedLengthDecodingStateImpl(4);
        	session.setAttributeIfAbsent(PREFIX_DECODINGSTATE, state);
        }
        if(state !=null)
        {
        	state.decode(in, out);
        	if(state.getState().equals(FixedLengthDecodingStateImpl.SUCCESS))
        	{
        		session.removeAttribute(PREFIX_DECODINGSTATE);
        		state =null;
        		return true;
        	}
        }
		return false;
	}
}
public class FixedLengthDecodingStateImpl extends FixedLengthDecodingState
{
	public String state = "";
	public final static String SUCCESS = "SUCCESS";
	public FixedLengthDecodingStateImpl(int length)
	{
		super(length);
	}

	public String getState()
	{
		return state;
	}

	public void setState(String state)
	{
		this.state = state;
	}
	@Override
	protected DecodingState finishDecode(IoBuffer product, ProtocolDecoderOutput out) throws Exception
	{
		int i = product.getInt();
		out.write(i);
		this.state =FixedLengthDecodingStateImpl.SUCCESS;
		return this;
	}
}


编码器:

public class FixedLengthEncoder extends ProtocolEncoderAdapter
{
	@Override
	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception
	{
		  Integer i =(Integer)message;
		  IoBuffer buf = IoBuffer.allocate(4).setAutoExpand(true);
          buf.putInt(i);
          buf.flip();
          out.write(buf);
	}
}

业务逻辑处理类:

public class FixedLengthIoHandlerAdapter extends IoHandlerAdapter
{
	@Override
	public void messageReceived(IoSession session, Object message) throws Exception
	{
		System.out.println("messageReceived:"+message);
	}
	
}


apache mina:实现固定字节长度编码解码

标签:

原文地址:http://blog.csdn.net/sunning9001/article/details/51333547

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!