Computer Networks22 min readAdvanced

Sockets — The Programmer's View of the Network

Open a TCP connection, send bytes, read bytes — the API every higher-level library is built on.

A SOCKET is a programming abstraction for one endpoint of a network connection. The same API works for TCP, UDP, and Unix domain sockets. Once you understand sockets, every networked library suddenly makes sense.

A minimal TCP server in Python

import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("0.0.0.0", 8080))
server.listen(5)
print("Listening on 8080")

while True:
    client, addr = server.accept()    # blocks until a client connects
    print(f"Connected: {addr}")
    data = client.recv(1024)          # read up to 1024 bytes
    client.sendall(b"HTTP/1.1 200 OK\r\n\r\nHello!")
    client.close()

A minimal TCP client

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("example.com", 80))
client.sendall(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
print(client.recv(4096).decode())
client.close()
💡 Tip
These 10 lines on each side are LITERALLY what every HTTP library, web framework, and database driver wraps. Underneath, it's just bytes over a socket.