View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.codec;
17  
18  import static io.netty.util.internal.ObjectUtil.checkPositive;
19  
20  import io.netty.buffer.ByteBuf;
21  import io.netty.channel.ChannelHandlerContext;
22  
23  import java.util.List;
24  
25  /**
26   * A decoder that splits the received {@link ByteBuf}s by the fixed number
27   * of bytes. For example, if you received the following four fragmented packets:
28   * <pre>
29   * +---+----+------+----+
30   * | A | BC | DEFG | HI |
31   * +---+----+------+----+
32   * </pre>
33   * A {@link FixedLengthFrameDecoder}{@code (3)} will decode them into the
34   * following three packets with the fixed length:
35   * <pre>
36   * +-----+-----+-----+
37   * | ABC | DEF | GHI |
38   * +-----+-----+-----+
39   * </pre>
40   */
41  public class FixedLengthFrameDecoder extends ByteToMessageDecoder {
42  
43      private final int frameLength;
44  
45      /**
46       * Creates a new instance.
47       *
48       * @param frameLength the length of the frame
49       */
50      public FixedLengthFrameDecoder(int frameLength) {
51          checkPositive(frameLength, "frameLength");
52          this.frameLength = frameLength;
53      }
54  
55      @Override
56      protected final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
57          Object decoded = decode(ctx, in);
58          if (decoded != null) {
59              out.add(decoded);
60          }
61      }
62  
63      /**
64       * Create a frame out of the {@link ByteBuf} and return it.
65       *
66       * @param   ctx             the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
67       * @param   in              the {@link ByteBuf} from which to read data
68       * @return  frame           the {@link ByteBuf} which represent the frame or {@code null} if no frame could
69       *                          be created.
70       */
71      protected Object decode(
72              @SuppressWarnings("UnusedParameters") ChannelHandlerContext ctx, ByteBuf in) throws Exception {
73          if (in.readableBytes() < frameLength) {
74              return null;
75          } else {
76              return in.readRetainedSlice(frameLength);
77          }
78      }
79  }