Learn Python
>>> advanced_python.socket_programming

Socket Programming Basics in Python

#concept

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.

#how it works
1

import socket

Brings in the module, part of the standard library.

2

socket.socket(family, type) creates one

Typically AF_INET for standard internet addressing and SOCK_STREAM for a reliable, ordered TCP connection.

3

A server binds, listens, and accepts

.bind() claims an address, .listen() waits for connections, .accept() accepts one.

4

A client connects

.connect((host, port)) reaches out to a server at that specific address.

5

Both sides exchange raw bytes

Using .send() and .recv() once a connection is established.

#example
# server.py
import 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.py
import socket
 
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("localhost", 65432))
client.send(b"Hello, server!")
client.close()
Output
Server received: Hello, server!
1server.py creates a socket, binds it to a specific address and port, then waits for a connection with .listen() and .accept().
2client.py creates its own socket and actively reaches out to that same address with .connect().
3client.send(b"Hello, server!") sends raw bytes across the connection.
4The server’s conn.recv(1024) receives up to 1024 bytes and .decode() converts those raw bytes back into a readable string, which the server then prints.
#use cases
Understanding the low-level mechanism that HTTP, web browsers, and libraries like requests are ultimately built on top of
Building a simple custom client-server application, like a basic chat program
Learning networking fundamentals — addresses, ports, and the client/server model — hands-on
Appreciating why higher-level libraries exist, once the amount of manual work sockets require becomes clear

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.