Frage

I am trying to write a program to send and receive a serialized object over a Datagram channel using Java nio, but I am receiving a BufferUnderFlow exception when trying to read my object from the ObjectInputStream.

Currently I have the following code:

Sender:

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
}

Receiver:

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) {}
}

This is the exception I am getting:

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)

What is causing this BufferUnderflowException to be thrown? I can't figure it out. Both ByteBuffers are allocated the same amount of space, and the writeBuffer is not overflowing.

War es hilfreich?

Lösung

You have to flip() the buffer to get data out of it. NB you should be using limit(), not capacity(), in that line.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top