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