simultaneously read and write on the same socket in C or C++

Jimm picture Jimm · Oct 23, 2012 · Viewed 36.9k times · Source

I am implementing a simple server, that accepts a single connection and then uses that socket to simultaneously read and write messages from the read and write threads. What is the safe and easy way to simultaneously read and write from the same socket descriptor in c/c++ on linux? I dont need to worry about multiple threads read and writing from the same socket as there will be a single dedicated read and single dedicated write thread writing to the socket.

In the above scenario, is any kind of locking required?

Does the above scenario require non blocking socket?

Is there any opensource library, that would help in the above scenario?

Answer

Tony Delroy picture Tony Delroy · Oct 23, 2012

In the above scenario, is any kind of locking required?

None.

Does the above scenario require non blocking socket?

The bit you're probably worried about - the read and write threads on an established connection - do not need to be non-blocking if you're happy for those threads to sit there waiting to complete. That's normally one of the reasons you'd use threads rather than select or poll or async operations... keeps the code simpler too.

If the thread accepting new clients is happy to block in the call to accept(), then you're all good there too.

Still, there's one subtle issue with TCP servers you might want to keep in the back of your mind... if your program grows to handle multiple clients and have some periodic housekeeping to do. It's natural and tempting to use a select statement with a timeout to check for readability on the listening socket - which indicates a client connection attempt - then accept the connection. There's a race condition there: the client connection attempt may have dropped between select() and accept(), in which case accept() will block if the listening socket's not non-blocking, and that can prevent a timely return to the select() loop and halt the periodic on-timeout processing until another client connects.

Is there any opensource library, that would help in the above scenario?

There are hundreds of libraries for writing basic servers, but ultimately what you've asked for is easily achieved atop OS-provided BSD sockets or their Windows bastardisation.