This program is the direct counterpart of the basic client example: it is the simplest possible program of its kind. This program simply sets up a listener on the network interface and port passed on the program's command line, accepts incoming connections, and echoes the remote peer's packets back to them.

The skeleton main() function in main.cpp calls our DoWinsock() function, which contains the main loop of the program. The function starts off by setting up the listener. This binds the program to a particular network interface and port and tells Winsock to forward all connection requests to the program.

The program then enters an endless loop to wait for connections. It accepts each incoming connection and then bounces packets back to the client until the client closes the connection. When that happens, the server closes its side of the socket and then goes back to waiting for connections.

Notice that you must pass an address on the command line to this program, due to the way the common main() function works. For this program, you can safely use "" all the time: when you bind() to the "any" address, Winsock sends incoming connections from any network interface to your program.

Interesting Behavior

This server exhibits some interesting behavior that you may want to experiment with:

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 basic-server.cpp. The comment at the top of the file gives complete compilation instructions; alternately, you can use the common Makefile.

<< CAsyncSocket-based Client
Multithreaded Server >>
Updated Sun Jan 18 2015 04:24 MST   Go to my home page