【发布时间】: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