Netty大字符串,没有足够的可读字节

时间:2012-11-21 22:20:14

标签: java string byte netty indexoutofboundsexception

我正在努力写一个'大'从我的服务器到我的客户端的字符串(986个字符),但在读取16个字符后出现以下错误:

not enough readable bytes - need 2, maximum is 0.

发送较小的字符串时它可以正常工作,但是如果有这么多字符,就会出现这个错误。

我们正在使用BigEndianHeapChannelBuffer来接收我们的数据。

来自write的obj.length()和来自read的buffer.readUnsignedShort()都给出了相同的(正确的)数字,但其余部分在for循环中崩溃。

Netty版本是3.5.10 FINAL

有人有任何想法如何解决这个问题?请询问您是否需要更多信息。

以下是一些代码段:

写给流:

public void addString(String obj)
{
  try
  {
    bodystream.writeShort(obj.length());
    bodystream.writeChars(obj);
    System.out.println("Server wrote bytes: " + obj.length());
    message = message + ";STRING: " + obj;
    // bodystream.w(obj);
  }
  catch(IOException e)
  {
  }
}    

从STREAM阅读:

public String readString()
{
  try
  {
    int len = buffer.readUnsignedShort();
    System.out.println("Client can read bytes: " + len);

    char[] characters = new char[len];
    for(int i = 0; i < len; i++)
      characters[i] = buffer.readChar();

    return new String(characters);
  }
  catch(Exception e)
  {
    System.err.println(e.getMessage());
    return "";
  }
}

解码:

public class NetworkDecoder extends FrameDecoder
{
  @Override
  protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer)
  {
    try
    {
      int opcode = buffer.readUnsignedByte();
      System.out.println("[In] <- " + opcode);
      return new ServerMessage(buffer, opcode);
    }
    catch(Exception e)
    {
      e.printStackTrace();
    }
    return null;
  }
}        

1 个答案:

答案 0 :(得分:0)

在将缓冲区传递给ServerMessage之前,您需要确保缓冲区中有足够的数据。你也想把ChannelBuffer.readBytes(..)调用到&#34;复制数据,否则你会吸收内存。