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