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