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.MessageToMessageDecoder;
23
24 /**
25 * Decodes a received {@link Buffer} into an array of bytes.
26 * A typical setup for TCP/IP would be:
27 * <pre>
28 * {@link ChannelPipeline} pipeline = ...;
29 *
30 * // Decoders
31 * pipeline.addLast("frameDecoder",
32 * new {@link LengthFieldBasedFrameDecoder}(1048576, 0, 4, 0, 4));
33 * pipeline.addLast("bytesDecoder",
34 * new {@link ByteArrayDecoder}());
35 *
36 * // Encoder
37 * pipeline.addLast("frameEncoder", new {@link LengthFieldPrepender}(4));
38 * pipeline.addLast("bytesEncoder", new {@link ByteArrayEncoder}());
39 * </pre>
40 * and then you can use an array of bytes instead of a {@link Buffer}
41 * as a message:
42 * <pre>
43 * void channelRead({@link ChannelHandlerContext} ctx, byte[] bytes) {
44 * ...
45 * }
46 * </pre>
47 */
48 public class ByteArrayDecoder extends MessageToMessageDecoder<Buffer> {
49 @Override
50 protected void decode(ChannelHandlerContext ctx, Buffer msg) throws Exception {
51 // copy the ByteBuf content to a byte array
52 byte[] array = new byte[msg.readableBytes()];
53 msg.readBytes(array, 0, array.length);
54 ctx.fireChannelRead(array);
55 }
56 }