Accepting a Connection
Once the socket is listening for a connection, the program must handle connection requests on that socket.
To accept a connection on a socket
- Create a temporary SOCKET object called ClientSocket for accepting connections from clients.
Normally a server application would be designed to listen for connections from multiple clients. For high-performance servers, multiple threads are commonly used to handle the multiple client connections.
There are several different programming techniques using Winsock that can be used to listen for multiple client connections. One programming technique is to create a continuous loop that checks for connection requests using the listen function (see Listening on a Socket). If a connection request occurs, the application calls the accept, AcceptEx, or WSAAccept function and passes the work to another thread to handle the request. Several other programming techniques are possible.
Note that this basic example is very simple and does not use multiple threads. The example also just listens for and accepts only a single connection.
When the client connection has been accepted, a server application would normally pass the accepted client socket (the ClientSocket variable in the above sample code) to a worker thread or an I/O completion port and continue accepting additional connections. In this basic example, the server continues to the next step.
There are a number of other programming techniques that can be used to listen for and accept multiple connections. These include using the select or WSAPoll functions. Examples of some of these various programming techniques are illustrated in the Advanced Winsock Samples included with the Microsoft Windows Software Development Kit (SDK).
Note On Unix systems, a common programming technique for servers was for an application to listen for connections. When a connection was accepted, the parent process would call the fork function to create a new child process to handle the client connection, inheriting the socket from the parent. This programming technique is not supported on Windows, since the fork function is not supported. This technique is also not usually suitable for high-performance servers, since the resources needed to create a new process are much greater than those needed for a thread.
Next Step: Receiving and Sending Data on the Server