1

我正在尝试编写一个程序来使用 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 被抛出?我想不通。两个 ByteBuffer 都分配了相同数量的空间,并且 writeBuffer 没有溢出。

4

1 回答 1

3

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

于 2014-05-15T21:08:14.130 回答