Search code examples
javasocketsserializationnio

Sending objects through Java NIO non-blocking sockets


I am getting an exception when trying to use:

oos = new ObjectOutputStream(socketChannel.socket().getOutputStream());
oos.writeObject(o);

And this raises the exception:

java.nio.channels.IllegalBlockingModeException

Is it impossible to pass objects in non-blocking sockets? If it is, how should I proceed on passing message objects through the socket channels?

I've looked other places for this answer but couldn't find one...


Solution

  • You'll probably want to write your own ObjectOutputStream implementation that constructs a ByteBuffer and write()s it to the channel.

    With non-blocking sockets, you cannot directly use the channel's socket; you need to use the channel's read() and write() methods.

    When you write your own ObjectOutputStream, you'll mainly need to override the write() methods to buffer output and use the flush() method to write the buffer to the channel. Then, override the writeObject() method to look like this:

    public void writeObject(Object o) throws IOException {
        super.writeObject(o);
        flush();
    }
    

    to make sure the data gets written after each object write.