IntegerHeaderFrameDecoder.java 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package net.dnio.codec.intheader;
  2. import org.jboss.netty.buffer.ChannelBuffer;
  3. import org.jboss.netty.channel.Channel;
  4. import org.jboss.netty.channel.ChannelHandlerContext;
  5. import org.jboss.netty.handler.codec.frame.FrameDecoder;
  6. /**
  7. *
  8. * <p>
  9. * 因为Netty是异步发送和接收消息, 接收端每次只能接收1024字节的数据。
  10. * 因此超过1024字节的消息会被分割。利用次消息头则可以获得的完整的消息
  11. * </p>
  12. *
  13. * <pre>
  14. *
  15. * Created by IntelliJ IDEA.
  16. * User: zhenqin
  17. * Date: 13-6-4
  18. * Time: 下午8:10
  19. * To change this template use File | Settings | File Templates.
  20. *
  21. * </pre>
  22. *
  23. * @author zhenqin
  24. */
  25. public class IntegerHeaderFrameDecoder extends FrameDecoder {
  26. public IntegerHeaderFrameDecoder() {
  27. }
  28. public IntegerHeaderFrameDecoder(boolean unfold) {
  29. super(unfold);
  30. }
  31. @Override
  32. public Object decode(ChannelHandlerContext ctx,
  33. Channel channel,
  34. ChannelBuffer buf) throws Exception {
  35. // Make sure if the length field was received.
  36. if (buf.readableBytes() < 4) {
  37. // 消息长度小于4字节,则是不正确的消息
  38. return null;
  39. }
  40. // 给当前Reader 的Buffer做标记
  41. buf.markReaderIndex();
  42. // 取得消息头,得到该消息的真实长度
  43. int length = buf.readInt();
  44. // 如果此次buffer读取的消息长度小于消息头的长度,则说明消息没有完成
  45. if (buf.readableBytes() < length) {
  46. // 重置消息的Reader的位置
  47. buf.resetReaderIndex();
  48. return null;
  49. }
  50. // There's enough bytes in the buffer. Read it.
  51. //直到所有的消息都存在于Buffered时, 开始读取
  52. ChannelBuffer frame = buf.readBytes(length);
  53. // Successfully decoded a frame. Return the decoded frame.
  54. return frame;
  55. }
  56. }