1package muduo.codec; 2 3import java.util.zip.Adler32; 4 5import org.jboss.netty.buffer.BigEndianHeapChannelBuffer; 6import org.jboss.netty.buffer.ChannelBuffer; 7import org.jboss.netty.channel.Channel; 8import org.jboss.netty.channel.ChannelHandler.Sharable; 9import org.jboss.netty.channel.ChannelHandlerContext; 10import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; 11 12import com.google.protobuf.Message; 13 14@Sharable 15public class ProtobufEncoder extends OneToOneEncoder { 16 17 public ProtobufEncoder() { 18 super(); 19 } 20 21 @Override 22 public Object encode(ChannelHandlerContext ctx, Channel channel, Object obj) 23 throws Exception { 24 if (!(obj instanceof Message)) { 25 return obj; 26 } 27 Message message = (Message) obj; 28 String name = message.getDescriptorForType().getFullName(); 29 int size = message.getSerializedSize(); 30 ChannelBuffer buffer = new BigEndianHeapChannelBuffer(4 + name.length() + 1 + size + 4); 31 buffer.writeInt(name.length() + 1); 32 buffer.writeBytes(name.getBytes()); 33 buffer.writeZero(1); 34 buffer.writeBytes(message.toByteArray()); 35 36 Adler32 checksum = new Adler32(); 37 checksum.update(buffer.array(), buffer.arrayOffset(), buffer.readableBytes()); 38 buffer.writeInt((int) checksum.getValue()); 39 40 return buffer; 41 } 42} 43