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);
    }
    
}

 

转载于:https://www.cnblogs.com/Guoyutian/p/5121833.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值