mks
mks

Reputation: 309

Writing and Reading Objects over Java NIO non blocking SocketChannels

I am new to Socket programming, and I am trying to write a simple chat application.My server utilizes a HashSet of Strings to store user name information and I want to pass the HashSet from the server to the client. I was able to do this before with ObjectOutputStream and ObjectInputStream over regular Sockets. However, now I am using SocketChannel and it does not allow this I get the following exception:

java.nio.channels.IllegalBlockingModeException

So i searched the web on how to do this and everyone says something different, and most go way over my head. Is there a simple way to do this without completely overriding the writeObject and readObject methods myself?

Thank You in advance.

Upvotes: 1

Views: 606

Answers (1)

user207421
user207421

Reputation: 310850

I recommend you either don't use non-blocking mode or don't use serialization.

If you must, you need to serialize to a ByteArrayOutputStream, get the length, send the length, send the bytes, receive the length, keep reading, accumulating data until you have the correct length of data, put it into a ByteArrayInputStream, and deserialize from that. Not easy, especially the hand-waving around 'keep reading'. And it wastes both time and space.

Upvotes: 2

Related Questions