2013-03-17 75 views
0
public class ServerPipelineFactory implements ChannelPipelineFactory { 
    @Override 
    public ChannelPipeline getPipeline() throws Exception { 
     PacketFrameDecoder decoder = new PacketFrameDecoder(); 
     PacketFrameEncoder encoder = new PacketFrameEncoder(); 
     return Channels.pipeline(decoder, encoder, new Handler()); 
    } 
} 

和我的解碼器讀取字節的Netty服務器

public class PacketFrameDecoder extends 
     ReplayingDecoder<PacketFrameDecoder.DecoderState> { 
    public enum DecoderState { 
     READ_CONTENT; 
    } 

    private int length; 

    public PacketFrameDecoder() { 
     super(DecoderState.READ_CONTENT); 
    } 

    @Override 
    protected Object decode(ChannelHandlerContext chc, Channel chnl, 
      ChannelBuffer cb, DecoderState state) throws Exception { 
     switch (state) { 

     case READ_CONTENT: 

      for (int i = 0; i < cb.capacity(); i ++) { 
       byte b = cb.getByte(i); 
       System.out.println((char) b); 
      } 

      return null; 
     default: 
      throw new Error("Shouldn't reach here."); 
     } 
    } 
} 

我發送消息

Socket fromserver = new Socket("localhost", 7283); 
PrintWriter out = new PrintWriter(fromserver.getOutputStream(), true); 
int data = 12; 
out.write(data); 
out.flush(); 
out.close(); 
fromserver.close(); 

但是當我bytes- 我有cb.capacity()= 256 和消息「?0?0」System.out.println((char) b);

請幫忙

回答

1

使用容量錯誤它是緩衝區中「最大」字節數量。另外從位置0開始是錯誤的,因爲readerIndex可能位於其他位置。請閱讀ChannelBuffer的apidocs,這些都詳細解釋了這一點。