我正在尝试编写一个程序,使用Java nio通过数据报通道发送和接收序列化对象,但是在尝试从ObjectInputStream中读取对象时,我收到了一个BufferUnderFlow异常。
目前我有以下代码:
发信人:
public void sendMessage(InetSocketAddress destination) {
writeBuffer = ByteBuffer.allocate(64000);
writeBuffer.clear();
/*
* Put new MyObject into a ByteArrayOutputStream and put that
* into the writeBuffer to be sent.
*/
MyObject myObject = new MyObject();
byteArrayOS = new ByteArrayOutputStream(writeBuffer.capacity());
objectOS = new ObjectOutputStream(byteArrayOS);
objectOS.writeObject(myObject);
objectOS.flush();
writeBuffer.put(byteArrayOS.toByteArray());
writeBuffer.flip();
channel.send(writeBuffer, new InetSocketAddress(ipAddress, portNum));
// Channel is bound to correct IP / Port
}
接收器:
public void read() {
try { //blah blah
channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(readPort));
channel.configureBlocking(true);
ByteArrayInputStream byteArrayIS = null;
ObjectInputStream objectIS = null;
MyObject object;
while (true) {
inputBuffer.clear();
client.getChannel().receive(inputBuffer);
byte[] data = new byte[inputBuffer.capacity()];
inputBuffer.get(data);
/*
* Troubleshooting: inputBuffer is returning with something
*/
byteArrayIS = new ByteArrayInputStream(data);
objectIS = new ObjectInputStream(byteArrayIS);
myObject = objectIS.readObject(); // Throwing BufferUnderflowException here
// Process object
// ...
}
} catch (BlahBlah e) {}
}
这是我得到的例外:
Exception in thread "main" java.nio.BufferUnderflowException
at java.nio.HeapByteBuffer.get(HeapByteBuffer.java:145)
at java.nio.ByteBuffer.get(ByteBuffer.java:694)
at package.Class.main(Class.java:493)
是什么导致抛出此BufferUnderflowException?我无法弄明白。两个ByteBuffers都分配了相同的空间量,而writeBuffer没有溢出。
答案 0 :(得分:3)
你必须翻转()缓冲区才能从中获取数据。注意,您应该在该行中使用limit()而不是capacity()。