Winsock Programmer’s FAQ Basic Winsock Examples: Basic Blocking Server |
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 "0.0.0.0" all the time: when
you bind()
to the "any" address, Winsock sends incoming
connections from any network interface to your program.
This server exhibits some interesting behavior that you may want to experiment with:
listen()
call. That additional client will then send data which the
stack will queue up, but it won't see a reply until the first
client disconnects so that the server can accept()
this
subsequent connection. Prove this to yourself by running two
copies of basic-client against
this server with the "shutdown delay" set to some largish
value. Then try running three copies of basic-client.
netstat
command line program
while basic-server is running to see its listener record. (Note
that netstat may only work correctly for this under Windows NT
derivatives.)
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 Fri Dec 16 2022 12:23 MST | Go to my home page |