1package muduo.rpc; 2 3import java.nio.charset.Charset; 4import java.util.zip.Adler32; 5 6import muduo.rpc.proto.RpcProto.RpcMessage; 7 8import org.jboss.netty.buffer.ChannelBuffer; 9import org.jboss.netty.channel.Channel; 10import org.jboss.netty.channel.ChannelHandlerContext; 11import org.jboss.netty.handler.codec.oneone.OneToOneDecoder; 12import org.jboss.netty.channel.ChannelHandler.Sharable; 13 14@Sharable 15public class RpcDecoder extends OneToOneDecoder { 16 17 @Override 18 public Object decode(ChannelHandlerContext ctx, Channel channel, Object obj) 19 throws Exception { 20 if (obj instanceof ChannelBuffer) { 21 ChannelBuffer buffer = (ChannelBuffer) obj; 22 if (buffer.readableBytes() > 8) { 23 String version = buffer.toString(buffer.readerIndex(), 4, Charset.defaultCharset()); 24 if (version.equals("RPC0")) { 25 Adler32 adler32 = new Adler32(); 26 adler32.update(buffer.array(), 27 buffer.arrayOffset() + buffer.readerIndex(), 28 buffer.readableBytes() - 4); 29 buffer.markReaderIndex(); 30 buffer.readerIndex(buffer.writerIndex() - 4); 31 int checksum = buffer.readInt(); 32 if (checksum == (int)adler32.getValue()) { 33 buffer.resetReaderIndex(); 34 RpcMessage message = RpcMessage.newBuilder().mergeFrom( 35 buffer.array(), 36 buffer.arrayOffset() + buffer.readerIndex() + 4, 37 buffer.readableBytes() - 8).build(); 38 return message; 39 } 40 } 41 } 42 } 43 return obj; 44 } 45} 46