Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 748
alexgolec Avatar asked Apr 14 '11 20:04

alexgolec


2 Answers

TCP socket is a full-duplex stream, you can read from and write to it from multiple threads. Whether doing so is a good idea is a totally different question.

like image 177
Nikolai Fetissov Avatar answered Oct 02 '22 20:10

Nikolai Fetissov


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.

like image 22
ikegami Avatar answered Oct 02 '22 19:10

ikegami