Introduction
A socket is the programming interface that lets an application send and receive data over a network. It is the endpoint of a two-way communication link, identified by an IP address and a port number. Nearly every networked application — web browsers, chat apps, game servers — is built on top of sockets, even if higher-level libraries hide the details. Understanding socket programming means understanding the actual sequence of system calls a program makes to establish and use a connection.
Cricket analogy: A socket is like a specific stump-mic feed identified by which stump and which broadcaster's channel it's wired to — every broadcast, from a small local match to a major international game, ultimately relies on this same basic wiring, even if commentators never think about the cables themselves.
Explanation
In Python, the socket module wraps the underlying operating system socket API. Creating a socket with socket.socket(socket.AF_INET, socket.SOCK_STREAM) requests an IPv4 (AF_INET) TCP (SOCK_STREAM) socket; using SOCK_DGRAM instead would request UDP. A server-side program typically follows this sequence: bind() attaches the socket to a specific local address and port, listen() puts the socket into a passive state where it queues incoming connection requests, and accept() blocks until a client connects, then returns a new socket object representing that specific connection along with the client's address. A client-side program instead calls connect() with the server's address and port to initiate a TCP three-way handshake. Once a connection exists (on either side), both ends use send()/sendall() to transmit bytes and recv() to read bytes, exchanging data until one side closes the socket with close().
Cricket analogy: Setting up a match is like requesting a specific format upfront — Test cricket (TCP, reliable) versus a quick exhibition T10 (UDP, fast); the host ground reserves the venue and date (bind), opens ticket sales for spectators (listen), and welcomes the visiting team on arrival (accept), while the visiting team's request to travel there triggers the whole itinerary (connect), and both sides exchange overs and updates (send/recv) until the match ends (close).
Example
# --- server.py: minimal TCP echo server ---
import socket
HOST = '0.0.0.0'
PORT = 65432
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen()
print(f"Listening on {HOST}:{PORT}")
conn, addr = server_socket.accept()
with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data) # echo the bytes back
server_socket.close()
# --- client.py: minimal TCP client ---
import socket
HOST = '127.0.0.1'
PORT = 65432
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))
client_socket.sendall(b'Hello, server')
data = client_socket.recv(1024)
client_socket.close()
print(f"Received: {data!r}")Analysis
The server example shows the classic bind-listen-accept pattern: bind() reserves port 65432 on all local interfaces, listen() makes the socket ready to queue incoming connection attempts (the OS handles the underlying TCP three-way handshake automatically), and accept() returns a brand-new socket object dedicated to that one client, leaving the original server_socket free to accept further connections in a real multi-client server (typically via threading or an event loop). The client's connect() call triggers the handshake from the other side. Note that recv(1024) does not guarantee 1024 bytes will be read — TCP is a stream protocol with no built-in message boundaries, so recv() may return fewer bytes than requested, and real applications must implement their own framing (e.g., length prefixes or delimiters) to know when a full message has arrived. This example works for a single request-response exchange but a production server would loop accept() to serve multiple clients concurrently.
Cricket analogy: A stadium reserves gate 65432 for all arriving spectators regardless of which entrance they approach from (bind on all interfaces), opens the turnstile queue (listen, with security handling the ID check automatically like the OS handles the handshake), and assigns each spectator their own personal usher once through (accept returns a dedicated connection), leaving the main gate free for the next arrival — but note an usher grabbing "the next 1024 spectators" might only get a partial batch since crowds don't arrive in neat fixed groups (recv doesn't guarantee full reads), so a real event needs its own headcount system (framing), and a real stadium loops this process all day for every match (production accept loop), not just once.
Key Takeaways
- socket.socket(AF_INET, SOCK_STREAM) creates a TCP socket; SOCK_DGRAM would create a UDP socket instead.
- Server flow: bind() reserves an address/port, listen() queues incoming connections, accept() returns a new socket for each connected client.
- Client flow: connect() initiates the TCP handshake to a server's address and port.
- send()/sendall() write bytes and recv() reads bytes; TCP is a byte stream with no built-in message boundaries, so recv() may return partial data.
Practice what you learned
1. Which socket() arguments create an IPv4 TCP socket in Python?
2. What does the listen() call do on a server socket?
3. What does accept() return on a TCP server?
4. Why might conn.recv(1024) return fewer than 1024 bytes even if the client sent more data than that?
Was this page helpful?
You May Also Like
Ports and Sockets
Understand port number ranges and how a socket, the pairing of an IP address and port, identifies a network endpoint.
The TCP Three-Way Handshake
Trace how TCP establishes a reliable connection using the SYN, SYN-ACK, and ACK exchange.
TCP vs UDP
Compare TCP and UDP across reliability, ordering, connection state, overhead, and typical use cases.
Transport Layer Basics
Learn how the transport layer provides process-to-process delivery between applications running on different hosts.