alexgolec
alexgolec

Reputation: 28252

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?

Upvotes: 10

Views: 9132

Answers (4)

ikegami
ikegami

Reputation: 385917

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.

Upvotes: 5

lobster1234
lobster1234

Reputation: 7779

Yes you can do that. You can have 1 thread start a server using ServerSocket, and another thread connecting to this Server via Socket. You can google for plenty of examples for EchoServer/EchoClient to get started.

Upvotes: 2

Zuljin
Zuljin

Reputation: 2640

As far as I know sockets are thread safe. You should only be careful when you call close() on socket from one thread. Second one could hang on some blocking function or select infinitely.

Upvotes: 2

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84189

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.

Upvotes: 11

Related Questions