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

一.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;
    }

}

 

@Sharable
public class EventDecoder extends OneToOneDecoder
{
    private static final Logger LOG = LoggerFactory.getLogger(EventDecoder.class);
    
    @Override
    protected Object decode(ChannelHandlerContext ctx, Channel channel,
            Object msg) throws Exception
    {
        if(null == msg)
        {
            LOG.error("Null msg received in EventDecoder");
            return msg;
        }
        ChannelBuffer buffer = (ChannelBuffer)msg;
        int opcode = buffer.readUnsignedByte();
        if(Events.LOG_IN == opcode || Events.RECONNECT == opcode){
            buffer.readUnsignedByte();// To read-destroy the protocol version byte.
        }
        return Events.event(buffer, opcode);
    }
    
}

 

你可能感兴趣的:(Jetserver开源项目学习(八)—— 解码编码器的用法)