gpt4 book ai didi

使用 DatagramChannels 和序列化时的 Java NIO BufferUnderflowException

转载 作者:行者123 更新时间:2023-11-29 05:23:31 24 4
gpt4 key购买 nike

我正在尝试编写一个程序来使用 Java nio 通过数据报 channel 发送和接收序列化对象,但在尝试从 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?我想不通。两个 ByteBuffer 都分配了相同数量的空间,并且 writeBuffer 没有溢出。

最佳答案

您必须 flip() 缓冲区才能从中获取数据。注意,您应该在该行中使用 limit(),而不是 capacity()。

关于使用 DatagramChannels 和序列化时的 Java NIO BufferUnderflowException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23683187/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com