【问题标题】:Netty large string, not enough readable bytesNetty 大字符串,没有足够的可读字节
【发布时间】:2012-11-10 06:43:15
【问题描述】:

我正在尝试将“大”字符串(986 个字符)从我的服务器写入我的客户端,但在读取 16 个字符后出现以下错误:

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

在发送较小的字符串时它可以正常工作,但是对于这么多的字符会引发此错误。

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

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

Netty 版本是 3.5.10 FINAL

有人知道如何解决这个问题吗?如果您需要更多信息,请询问。

下面是一些代码sn-ps:

写入流:

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)
  {
  }
}    

从流中阅读:

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;
  }
}        

【问题讨论】:

  • 只是想对这段代码进行推理,您将字符串的长度计算为无符号短,然后将其后跟字符串返回到流中,然后在阅读时采用无符号短出,并确定你将阅读多长时间?解码对此有何影响?
  • 你不能通过删除作者的长度提示并在 ChannelBuffer 上调用 .toString() 来简化这个吗?
  • 嗯,这听起来太明显了,不可能是真的。但我现在试试看。
  • screensnapr.com/v/PadniK.jpg 这是我现在得到的输出,所有这些 0,0,0,1,2,0,0..... 都作为 1 个字符串从服务器发送。跨度>

标签: java string byte netty indexoutofboundsexception


【解决方案1】:

在将缓冲区传递给 ServerMessage 之前,您需要确保缓冲区中有足够的数据。你也想调用 ChannelBuffer.readBytes(..) 来“复制数据,否则你会占用内存。

【讨论】:

  • 我将尝试使用 FrameDecoder 文档中给出的示例来进行归档。
猜你喜欢
  • 1970-01-01
  • 2021-03-08
  • 2012-01-13
  • 2013-08-02
  • 2017-12-09
  • 2012-07-09
  • 1970-01-01
  • 2014-04-07
  • 1970-01-01
相关资源
最近更新 更多