1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- package net.dnio.codec.intheader;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.jboss.netty.buffer.ChannelBuffer;
- import org.jboss.netty.buffer.ChannelBuffers;
- import org.jboss.netty.channel.Channel;
- import org.jboss.netty.channel.ChannelHandlerContext;
- import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
- /**
- *
- * <p>
- * 该类会在消息头部写上一个标识消息长度的int的值。
- * 用于在接收端识别消息的总长度,从而得到一个完整的消息体。
- * </p>
- *
- *
- * <p>
- * 因为Netty是异步发送和接收消息, 接收端每次只能接收1024字节的数据。
- * 因此超过1024字节的消息会被分割。利用次消息头则可以获得的完整的消息
- * </p>
- *
- * <pre>
- *
- * Created by IntelliJ IDEA.
- * User: zhenqin
- * Date: 13-6-4
- * Time: 下午8:10
- * To change this template use File | Settings | File Templates.
- *
- * </pre>
- *
- * @author zhenqin
- */
- public class IntegerHeaderFrameEncoder extends OneToOneEncoder {
- /**
- * 日志记录
- */
- private static Log log = LogFactory.getLog(IntegerHeaderFrameEncoder.class);
- public IntegerHeaderFrameEncoder() {
- }
- @Override
- public Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
- if (!(msg instanceof ChannelBuffer)) {
- return msg;
- }
- //取得消息正文
- ChannelBuffer body = (ChannelBuffer) msg;
- //构造一个和原消息等长的消息, 并且加上一个int所占用的内存
- ChannelBuffer buffer = ChannelBuffers.buffer(body.capacity() + 4);
- //写入消息长度
- buffer.writeInt(body.writerIndex());
- //写入消息
- buffer.writeBytes(body);
- //返回一个构造的完整的消息
- return buffer;
- }
- }
|