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

バッファからデータを取得するには、バッファを flip() する必要があります。注意: その行では、capacity() ではなく limit() を使用する必要があります。

于 2014-05-15T21:08:14.130 に答える