标签:
一.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; } }
标签:
原文地址:http://www.cnblogs.com/Guoyutian/p/5121833.html