1
我發現一個問題,當通過TCP發送數據時,依賴於知道數據長度的自定義協議,所以我決定由於int的大小而不能發送int可能是不同的長度(int 10的長度爲2,而int 100的長度爲3),所以我決定發送一個4字節的int表示形式,因此我遇到了ByteBuffer。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()'和朋友。 – EJP 2014-09-20 10:18:16