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