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.netty5.handler.codec.bytes;
17  
18  import io.netty5.buffer.api.Buffer;
19  import io.netty5.channel.ChannelHandlerContext;
20  import io.netty5.channel.ChannelPipeline;
21  import io.netty5.handler.codec.LengthFieldPrepender;
22  import io.netty5.handler.codec.MessageToMessageEncoder;
23  
24  import java.util.List;
25  
26  /**
27   * Encodes the requested array of bytes into a {@link Buffer}.
28   * A typical setup for TCP/IP would be:
29   * <pre>
30   * {@link ChannelPipeline} pipeline = ...;
31   *
32   * // Decoders
33   * pipeline.addLast("frameDecoder",
34   *                  new {@link LengthFieldBasedFrameDecoder}(1048576, 0, 4, 0, 4));
35   * pipeline.addLast("bytesDecoder",
36   *                  new {@link ByteArrayDecoder}());
37   *
38   * // Encoder
39   * pipeline.addLast("frameEncoder", new {@link LengthFieldPrepender}(4));
40   * pipeline.addLast("bytesEncoder", new {@link ByteArrayEncoder}());
41   * </pre>
42   * and then you can use an array of bytes instead of a {@link Buffer}
43   * as a message:
44   * <pre>
45   * void channelRead({@link ChannelHandlerContext} ctx, byte[] bytes) {
46   *     ...
47   * }
48   * </pre>
49   */
50  public class ByteArrayEncoder extends MessageToMessageEncoder<byte[]> {
51  
52      @Override
53      public boolean isSharable() {
54          return true;
55      }
56  
57      @Override
58      protected void encode(ChannelHandlerContext ctx, byte[] msg, List<Object> out) throws Exception {
59          out.add(ctx.bufferAllocator().copyOf(msg));
60      }
61  }