TExcelTAD
Home › Computer Networking › Socket Programming

Socket Programming

The socket API is how programs use the network. It was designed for BSD Unix in 1983 and has been copied by every operating system and language since. Once you know the handful of calls, you can read networking code in C, Python, Go, Java or Rust.

Note: Browsers don't let web pages open raw sockets, so the real client and server programs in this lesson are plain listings for you to run on your own computer. The runnable examples model what those calls do: framing messages, buffering and building a tiny protocol.

The calls

Server Client What it does
socket() socket() create a socket (family + type: TCP or UDP)
bind(addr, port) (optional) attach to a local address and port
listen(backlog) mark it as a passive, listening socket
accept() wait for a client; returns a new socket for that connection
connect(addr, port) perform the TCP handshake
recv() / send() send() / recv() exchange bytes
close() close() send FIN, release the socket

A TCP echo server and client

python
# echo_server.py
import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)   # restart without "address in use"
    server.bind(("127.0.0.1", 5000))
    server.listen()
    print("listening on 127.0.0.1:5000")
    while True:
        conn, addr = server.accept()          # blocks until a client connects
        with conn:
            print("connection from", addr)
            while data := conn.recv(4096):    # b"" means the client closed its side
                conn.sendall(data.upper())
python
# echo_client.py
import socket

with socket.create_connection(("127.0.0.1", 5000), timeout=5) as sock:
    sock.sendall(b"hello, sockets\n")
    print(sock.recv(4096))

Run the server in one terminal and the client in another:

text
$ python3 echo_server.py
listening on 127.0.0.1:5000
connection from ('127.0.0.1', 51790)

$ python3 echo_client.py
b'HELLO, SOCKETS\n'

Three mistakes almost everyone makes once:

  1. Using send() instead of sendall(). send() may write only part of the data and returns how many bytes it sent.
  2. Assuming one recv() returns one whole message. TCP is a byte stream: a message can arrive split across several recv() calls, or several messages can arrive in one.
  3. Forgetting that recv() returning b"" means the peer closed the connection, not "no data yet".

Framing messages

Because TCP has no message boundaries, every protocol defines its own framing. The two common choices are a delimiter (HTTP/1.1 headers and SMTP end lines with \r\n) and a length prefix (most binary protocols). Here's a receiver that handles both correctly, no matter how the stream is cut:

python · try it yourself
import struct

class LineReader:
    def __init__(self):
        self.buffer = b""

    def feed(self, chunk):
        self.buffer += chunk
        lines = []
        while b"\r\n" in self.buffer:
            line, self.buffer = self.buffer.split(b"\r\n", 1)
            lines.append(line.decode())
        return lines

class LengthPrefixedReader:
    def __init__(self):
        self.buffer = b""

    def feed(self, chunk):
        self.buffer += chunk
        messages = []
        while len(self.buffer) >= 4:
            (length,) = struct.unpack("!I", self.buffer[:4])
            if len(self.buffer) < 4 + length:
                break                      # wait for the rest of this message
            messages.append(self.buffer[4:4 + length].decode())
            self.buffer = self.buffer[4 + length:]
        return messages

lines = LineReader()
for chunk in [b"HELO cli", b"ent.example\r\nMAIL FROM:<a@exa", b"mple.com>\r\nRCPT"]:
    print("chunk", chunk, "->", lines.feed(chunk))

frames = LengthPrefixedReader()
stream = b"".join(struct.pack("!I", len(m)) + m for m in [b"ping", b"temperature=21.5", b"bye"])
for start in range(0, len(stream), 7):            # deliver the stream 7 bytes at a time
    got = frames.feed(stream[start:start + 7])
    if got:
        print(f"after byte {min(start + 7, len(stream)):>2}: {got}")
chunk b'HELO cli' -> []
chunk b'ent.example\r\nMAIL FROM:<a@exa' -> ['HELO client.example']
chunk b'mple.com>\r\nRCPT' -> ['MAIL FROM:<a@example.com>']
after byte 14: ['ping']
after byte 28: ['temperature=21.5']
after byte 35: ['bye']

A request/response protocol over a simulated connection

To see client and server logic together, we can connect them with an in-memory "socket pair" that splits data into small chunks like a real network might:

python · try it yourself
class FakeSocket:
    """One direction of a connection that delivers data in chunks of at most `mtu` bytes."""
    def __init__(self, mtu):
        self.mtu, self.queue = mtu, b""

    def sendall(self, data):
        self.queue += data

    def recv(self, n):
        n = min(n, self.mtu)
        chunk, self.queue = self.queue[:n], self.queue[n:]
        return chunk

def read_line(sock, buffered):
    while b"\n" not in buffered:
        buffered += sock.recv(4096)
    line, rest = buffered.split(b"\n", 1)
    return line.decode(), rest

STORE = {"alice": "42", "bob": "7"}

def server_handle(line):
    command, *args = line.split()
    if command == "GET":
        return f"OK {STORE[args[0]]}" if args[0] in STORE else "ERR not found"
    if command == "SET":
        STORE[args[0]] = args[1]
        return "OK"
    return "ERR unknown command"

to_server, to_client = FakeSocket(mtu=5), FakeSocket(mtu=3)
server_buf = client_buf = b""
for request in ["GET alice", "SET carol 99", "GET carol", "GET dave", "DELETE bob"]:
    to_server.sendall(request.encode() + b"\n")                    # client sends
    line, server_buf = read_line(to_server, server_buf)            # server reads a full line
    to_client.sendall(server_handle(line).encode() + b"\n")       # server replies
    reply, client_buf = read_line(to_client, client_buf)           # client reads a full line
    print(f"{request:<13} -> {reply}")
GET alice     -> OK 42
SET carol 99  -> OK
GET carol     -> OK 99
GET dave      -> ERR not found
DELETE bob    -> ERR unknown command

Even though the fake network delivered at most 5 (or 3) bytes per recv(), every request and reply arrived intact because both sides frame by newline and buffer until a full line is present.

Handling many clients

A server that handles one client at a time is useless in practice. The main approaches:

Model How Example
Thread (or process) per connection accept(), then hand the socket to a new thread classic Apache, simple Java servers
Event loop with non-blocking sockets select/epoll/kqueue tell you which sockets are ready nginx, Node.js, Redis
async/await an event loop with nicer syntax Python asyncio, Rust tokio, C#
python
# asyncio echo server: thousands of clients on one thread
import asyncio

async def handle(reader, writer):
    while line := await reader.readline():
        writer.write(line.upper())
        await writer.drain()
    writer.close()

async def main():
    server = await asyncio.start_server(handle, "127.0.0.1", 5000)
    async with server:
        await server.serve_forever()

asyncio.run(main())

Test any line-based TCP server from a terminal with netcat:

bash
printf 'hello\nworld\n' | nc 127.0.0.1 5000

Sample output:

text
HELLO
WORLD

Tip: Always set timeouts on client sockets (settimeout, or timeout= in create_connection). Without one, a client talking to a dead server can hang forever.

Test yourself

What does accept() return on a listening TCP socket?

  1. The number of bytes received
  2. A new socket for the accepted connection (plus the client address)
  3. The server's own address
  4. Nothing; it only blocks

Why must a TCP protocol define framing?

  1. TCP encrypts messages
  2. TCP is a byte stream with no message boundaries
  3. Routers merge packets
  4. Because UDP does

What does recv() returning an empty bytes object (b'') mean?

  1. No data yet, try again
  2. The peer closed the connection
  3. An error occurred
  4. The buffer is full