TCP Server: Listen and Accept
What you'll learn: How a TCP server transitions from a bound socket to actively listening for and accepting incoming client connections.
The Server's Waiting Room
After creating and binding a TCP socket to an address and port (covered previously), your server needs to start listening for connection requests. Think of this like opening a restaurant: you've secured the building and hung your address sign (binding), but now you need to unlock the door and be ready to seat guests.
Listen: Opening for Business
The listen() operation puts your server socket into passive mode, signaling that it's ready to accept incoming connections. This function takes a parameter called the backlog, which specifies how many pending connection requests can queue up while your server is busy handling others.
listen(server_socket, backlog)
The backlog acts like a waiting area. If clients attempt to connect while you're serving others, they'll wait in this queue rather than being immediately rejected.
Accept: Greeting Each Client
The accept() operation is blocking by default—it waits until a client attempts to connect. When a connection request arrives, accept() completes the TCP three-way handshake and returns a new socket specifically for communicating with that client.
client_socket, client_address = accept(server_socket)
This is crucial: your original server socket continues listening, while the new client socket handles that specific conversation. This allows your server to manage multiple clients—one conversation per accepted socket.
The Pattern
- Create and bind server socket
- Call
listen()to enter passive mode - Call
accept()repeatedly to handle each client - Each
accept()returns a dedicated client socket
Key Takeaway: listen() prepares your server socket to queue incoming connections, while accept() creates individual sockets for each client conversation, enabling concurrent communication without losing the ability to accept new clients.