We’re building an async thread per client server and stumbled upon a problem. We want the thread to always be ready to either read or write to\from the socket. We currently use the socket’s reading method which is blocking and as a result we cannot issue any write requests.
- is there a way to interrupt the read operation?
- perhaps it’s better to have the main server thread responsible for writing to the socket?
if so, does it still comply with the thread per client design pattern?
You should probably use separate threads, one for reading and one for writing, and use some kind of synchronization method (e.g., shared buffers guarded with mutexes) to communicate between the two. Also, the
selectcall can be used to see if there is any data pending on the socket.Update
I was originally thinking of the
select()function callable from C. Oh well.The closest thing that I can find in the Java API is
Socket.getInputStream(), which gives you a stream that can be tested to determine if bytes are available for reading or not from the underlying socket.