I have two separate java processes communicating over a single TCP connection. The protocol is not a simple synchronous request/response one like HTTP. Both sides may independently initiate requests and send data. I want to implement this using threads and blocking sockets, avoiding NIO. But is this even possible?
Java sockets (java.net.Socket) are not threadsafe, so i'm not allowed to read from the socket in one thread while simultaneously writing to it in another thread. (Is this true?) This restriction obviously leads to the possibility of deadlock, when both sides are blocked writing to the socket.
It follows that certain protocols on top of TCP can't be implemented开发者_开发技巧 in java without using NIO, or am i missing a point?
Thank you.
Full duplex communication is certainly possible. Without NIO, you'll need a thread to read from the socket (and perform the requested processing). Meanwhile, another thread can be writing to the same socket.
If you can point out some documentation that suggests that sockets are not full duplex, I'll try to clarify it.
I don't know where you've read that Java sockets are generally thread-unsafe. You can't have multiple threads simultaneously writing or reading from the socket's streams, but there's no reason why you can't have on thread writing to the socket's OutputStream and another thread reading from the socket's InputStream.
Sockets are thread safe so there's no problem with using multiple threads, one for reading and one for writing. On the other hand if you want to avoid multiple threads then you need to perform polling on the socket input stream to see if there's incoming data on a regular basis while you're performing whatever outbound operations you have.
精彩评论