Alex Rivera | Logout

Can I read and write on the same socket using two different threads?

Asked 2011-04-14T20:43:27.910
10

I'm writing a little thing for an assignment, and I have to manage TCP connections between hosts. My vision was originally two TCP connections, one incoming, one outgoing, and a really elaborate protocol to manage the creation and destruction of these connections.

So then, here is a simpler alternative that I hope works. One socket, easy to connect, easy to destroy. One thread writing data to the stream on that socket, one thread reading from the stream on that same socket. I have no problem with blocking, so I don't need to use nio for anything.

Can I make this happen?

Edit
Report

1 Answer

5

It would probably result in clearer and simpler code if you had only writer thread and only one reader thread.

Other threads wishing to communicate via that socket would pass requests to the writer thread via some queue. Similarly, the reader would dispatch incoming messages to the appropriate threads via queue.

This technique is commonly used for user interfaces.

answered 2011-04-14T21:06:49.667

Your Answer