Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 434
Draiken Avatar asked Sep 09 '26 07:09

Draiken


1 Answers

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.

like image 191
Jonathan Avatar answered Sep 12 '26 15:09

Jonathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!