2016-05-29 139 views
1

我创建了一个解码器来处理客户端发送的字节。 这里是ReplayingDecoder在解码时抛出异常

import java.util.List; 

import io.netty.buffer.ByteBuf; 
import io.netty.channel.ChannelHandlerContext; 
import io.netty.handler.codec.ReplayingDecoder; 

public class MessageDecoder extends ReplayingDecoder<DecoderState> { 

    private int length; 

    public MessageDecoder() 
    { 
     super(DecoderState.READ_LENGTH); 
    } 

    @Override 
    protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception{ 
     System.out.println(buf.readableBytes()); 
     switch(state()){ 
      case READ_LENGTH: 
       length=buf.readInt(); 
       System.out.println("length is: "+length); 
       checkpoint(DecoderState.READ_CONTENT); 
      case READ_CONTENT: 
       ByteBuf frame = buf.readBytes(length); 
       checkpoint(DecoderState.READ_LENGTH); 
       out.add(frame); 
       break; 
      default: 
       throw new Error("Shouldn't reach here"); 
     } 
    } 
} 

而当客户端发送的字节

io.netty.handler.codec.DecoderException它抛出一个错误:java.lang.IllegalArgumentException异常:minimumReadableBytes:-603652096(预期:> = 0) at io.netty.handler.codec.ReplayingDecoder.callDecode(ReplayingDecoder.java:431) at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:245) at io.netty .channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:292) 在io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:278) 在io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:962) 在io.netty.channel.nio.AbstractNioByteChannel $ NioByteUnsafe。读(AbstractNioByteChannel.java:131) 在io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:528) 在io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:485) 在io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:399) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:371) at io.netty.util.concurrent.SingleThreadEventExecutor $ 2 .run(SingleThreadEventExecutor.java:112) at io.netty.util.concurrent.DefaultThreadFactory $ DefaultRunnableDecorator.run(DefaultThreadFactory.java:137) 在java.lang.Thread.run(来源不明)

该代码是从官方文档http://netty.io/4.0/api/io/netty/handler/codec/ReplayingDecoder.html,所以我真不不明白为什么它不起作用

+0

btw当我发送4个字节它说我发送2147483647字节 – user2686299

回答

1

很可能远程对等体确实将int写入为unsigned。也许你想要使用readUnsignedInt()?

+0

但它有'长'型,它是8个字节不是吗?远程节点写入4个字节 – user2686299

+0

,而不会看到远程节点确切地讲述了什么。我可以告诉你的是,readInt()在这里返回一个负数。 –

+0

我的远程节点只发送一个整数值,4字节http://pastebin.com/NGmqK5PH但Netty说,当我使用System.out.println(buf.readableBytes())时,有2147483647个字节可用; – user2686299