码迷,mamicode.com
首页 > 其他好文 > 详细

Jetserver开源项目学习(八)—— 解码编码器的用法

时间:2016-01-11 18:19:54      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

一.EventEncoder和EventDecoder

事件编码器会收到一个事件对象(event object)并将它转换成为ChannelBuffer对象。编码器首先读取事件的类型并作为操作码(缓冲区的第一个字节),然后读取事件体并转换成为ChannelBuffer对象作为信息体。

/**
 * A simple event encoder will receive an incoming event, and convert it to a
 * {@link ChannelBuffer}. It will read the event type and put it as the
 * opcode(i.e first byte of the buffer), then it will read the event body and
 * put convert to ChannelBuffer if necessary and put it as the body of the
 * message.
 * 
 * @author Abraham Menacherry
 * 
 */
@Sharable
public class EventEncoder extends OneToOneEncoder
{
    private static final Logger LOG = LoggerFactory
            .getLogger(EventDecoder.class);

    @Override
    protected Object encode(ChannelHandlerContext ctx, Channel channel,
            Object msg) throws Exception
    {
        if (null == msg)
        {
            LOG.error("Received null message in EventEncoder");
            return msg;
        }
        Event event = (Event) msg;
        ChannelBuffer opcode = ChannelBuffers.buffer(1);
        opcode.writeByte(event.getType());
        ChannelBuffer buffer = null;
        if(null != event.getSource())
        {
            ChannelBuffer data = (ChannelBuffer) event.getSource();
            buffer = ChannelBuffers.wrappedBuffer(opcode, data);
        }
        else
        {
            buffer = opcode;
        }
        return buffer;
    }

}

 

Jetserver开源项目学习(八)—— 解码编码器的用法

标签:

原文地址:http://www.cnblogs.com/Guoyutian/p/5121833.html

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