Socket Programming Basics in Python
A socket is an endpoint for network communication, letting one program send and receive data over a network to another program, whether on the same machine or across the internet. Python's built-in socket module provides direct, low-level access to this — the same underlying mechanism that higher-level tools like web browsers and the requests library are ultimately built on top of.
import socket
Brings in the module, part of the standard library.
socket.socket(family, type) creates one
Typically AF_INET for standard internet addressing and SOCK_STREAM for a reliable, ordered TCP connection.
A server binds, listens, and accepts
.bind() claims an address, .listen() waits for connections, .accept() accepts one.
A client connects
.connect((host, port)) reaches out to a server at that specific address.
Both sides exchange raw bytes
Using .send() and .recv() once a connection is established.
# server.pyimport socket server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)server.bind(("localhost", 65432))server.listen() conn, addr = server.accept()data = conn.recv(1024)print(f"Server received: {data.decode()}")conn.close() # client.pyimport socket client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)client.connect(("localhost", 65432))client.send(b"Hello, server!")client.close()Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.