The threaded server is probably the simplest "real" server type to understand. A server program almost always needs to handle more than one connection at a time, and this is the simplest way to do that under Winsock. The reason is, since each connection gets its own thread, each thread can use simple blocking I/O on the socket. All other multi-connection server types use non-synchronous I/O of varying complexities in order to avoid thread overhead.

This server isn't that different from the basic single-connection server. The architectures are fairly different, but some of the code is identical between the two server programs.

In the basic server, the AcceptConnection() function is only two lines. The equivalent function in the threaded server, AcceptConnections(), is about 20 lines, because it sits in a loop waiting for connections, each of which it spins off into its own thread.

Each thread handles its connection more or less identically to the way the basic server handles each connection. In fact, the EchoIncomingPackets() is the same in each program. The only difference is that the main loop calls this function in the basic server, but it's called from the thread entry function in the threaded server. Similarly, the thread function shuts the connection down once the client stops sending packets; in the basic server, the main loop shuts client connections down.

Building the Program

The only module you will need to compile this program, aside from the common files listed on the main examples page, is threaded-server.cpp. The comment at the top of the file gives complete compilation instructions; alternately, you can use the common Makefile.

<< Basic Blocking Server
select()-based Server >>
Updated Fri Dec 16 2022 12:23 MST   Go to my home page