This is a collection of example network server implementations for Linux and Windows. You can use these as a starting point for your own server implementation.
This server can only handle one client at a time, with up to 10 clients (the backlog argument to listen), being allowed to wait before connections are refused.
This is suitable for a single-user desktop server or one in which connections are very short-lived.
This server uses the fork function to create a new process for each client connection, permitting as many clients as resources will allow.
It only works on Linux, and is best suited to server computers with 1 or 2 cores.
Notice that when using fork it is necessary to set up a signal handler for SIGCHLD in order to reap zombie processes.
This server creates a new thread for each client connection. This also permits as many connections as resources will allow. It is less resource intensive than forking. It is the only option for multiprocessing on Windows, and on Linux is best suited to server computers with more than 2 cores.
When using multiple threads it is necessary to use synchronisation locks when accessing any shared application state, and also when calling many socket API functions.
This server uses the select function to determine when sockets are ready for reading, and when clients have disconnected.
It is not as fast as forking or using threads, and cannot exploit multi-cores, but is less resource intensive, and so will scale up to far more connections.
In order to prevent the handling of individual clients from starving others, it may necessary to limit how much data is read per client in response to each select call.
Additionally, this example assumes that calls to recv will not block.
If they can block, it may be necessary to put the socket in non-blocking mode using fcntl with the F_SETFL command and the O_NONBLOCK flag.
Copyright (C) 2010 Martin Broadhurst