开发者

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 p开发者_运维知识库roceed on passing message objects through the socket channels?

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


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.


It's been a while since I worked in this area but it seemed to be more complex than simply wrapping writeObject. java.nio typically expects fixed size buffers (though you can dynamically allocate them I believe) and your remote endpoints need to know how much to read for an arbitrary Object coming down the wire. What I ended up doing was to send an initial int header telling the other end how much data to expect, and then serializing the object to a byte array and sending that down the wire.

I've got an example of this that may still have some bugs, so use at your own risk. The PendingDataBufferS are needed to deal with objects that are larger than the initially allocated fixed size buffer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜