简体   繁体   中英

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?

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM