I have written C code for a TCP server to listen to one client at a time.. but I’m having difficulty figuring out how I can get the server to listen to multiple clients at one time.
Does any one know of a good tutorial or example explaining this?
Thanks!
There are a number of ways to achieve this, some of which are:
selectto basically wait on a group of file descriptors until one of them is ready for reading or writing.pthreads, to hand off individual sessions to separate threads within the one process.forkto replicate the process for handling a session, so that the forked process handles that session and the original goes back to waiting for more connections.Of these, I prefer the middle one. Forking a process is a sometimes-expensive operation in that the data normally has to be copied if either process attempts to change it.
The
selectoption means that your code has to manage multiple sessions and that can sometimes get messy.With threading, you can separate relatively easily the sessions from each other, without incurring the cost of process duplication. Of course, threading has its own pitfalls if you’re not careful but I consider it a preferable option once you understand the potential problem areas.