views:

137

answers:

3

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?

+2  A: 

Use asynchronous (non-blocking) socket IO. Or you could also use a separate thread for writing.

alemjerus
+2  A: 

Make sure the socket is non-blocking (FIONBIO I think). And use select() to determine when data is ready to be read.

Mark Wilkins
how exactly does using non-blocking socket channels helps? should we just repeatedly check for read\write readiness? that seems a bit inefficient.
kfiroo
The select() function is what takes care of that. Use it to know when there is data to be read on a socket (or set of sockets). Then attempt to read data from the socket. The non-blocking option simply guarantees that the read on the socket will return immediately of no data exists.
Mark Wilkins
+1  A: 

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 select call 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.

Loadmaster
can you please elaborate about the select()? i cant found it in the socket api
kfiroo