【问题标题】:ByteBuffer causing underflow exceptionByteBuffer 导致下溢异常
【发布时间】:2014-09-20 18:27:51
【问题描述】:

我在使用依赖于知道数据长度的自定义协议通过 TCP 发送数据时遇到了一个问题,因此我决定不能发送 int,因为 int 的大小可能是不同的长度(int 10长度为 2 而 int 100 的长度为 3) 所以我决定发送一个 4 字节的 int 表示,因此我遇到了 ByteBuffer。

通过以下示例,我得到了一个 BufferUnderflowException

try
{
    int send = 2147483642;
    byte[] bytes = ByteBuffer.allocate(4).putInt(send).array(); // gets [127, -1, -1, -6]
    int recieve = ByteBuffer.allocate(4).put(bytes).getInt(); // expected 2147483642; throws BufferUnderflowException
    if (send == recieve)
    {
        System.out.println("WOOHOO");
    }
}
catch (BufferUnderflowException bufe)
{
    bufe.printStackTrace();
}

【问题讨论】:

  • 您忽略了flip(),但这似乎毫无意义。扔掉它,使用DataOutputStream.writeInt() 和朋友。

标签: java int bytearray bytebuffer bufferunderflowexception


【解决方案1】:

需要设置起始索引或倒带缓冲区;

int recieve = ByteBuffer.allocate(4).put(bytes).getInt(0);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 2018-09-03
    • 1970-01-01
    相关资源
    最近更新 更多