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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With