Tutorial
Building Real Connections: Getting Started with Python Sockets
Learn how to create a basic chat server and client using Python sockets in under 20 lines of code, understand TCP vs UDP, and avoid common pitfalls.
June 2026 · 5 min read · 1 views · 0 hearts
Advertisement
Building Real Connections: Getting Started with Python Sockets
Network programming sounds scary—firewalls, protocols, three-way handshakes, all that jargon. But when you strip it down, sockets are just Python's way of letting two programs talk to each other over a network. The best part? You can build a basic chat server in under 20 lines of code.
Let's jump straight into the core concept: a socket is an endpoint for sending and receiving data. Think of it like a phone line—you need to dial a number (IP address and port) to connect, then you can talk back and forth.
The Anatomy of a Socket Connection
Every socket connection has four key ingredients:
- IP address – where the machine lives
- Port number – which application to talk to
- Protocol – TCP for reliable connections, UDP for speed
- Socket family – typically AF_INET for IPv4
When you use socket.socket(socket.AF_INET, socket.SOCK_STREAM), you're saying: "I want an IPv4 connection using TCP."
Building a Simple Server in 10 Lines
Here's how you create a server that listens for one client:
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', 9999))
server.listen(1)
print("Server is listening on port 9999...")
conn, addr = server.accept() # Blocks until a client connects
print(f"Connected by {addr}")
data = conn.recv(1024) # Receive up to 1024 bytes
print(f"Received: {data.decode()}")
conn.sendall(b"Hello from server!")
conn.close()
That's it. The server sits there, waiting. When someone connects, it says "Hi" and hangs up. Simple, but powerful.
The Client Side – Even Simpler
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost', 9999))
client.sendall(b"Hello from client!")
response = client.recv(1024)
print(f"Server said: {response.decode()}")
client.close()
Run the server first, then the client. You'll see the handshake happen in real time—no frameworks, no magic.
Why TCP and Not UDP?
TCP (SOCK_STREAM) guarantees that your data arrives intact and in order. It's like registered mail. UDP (SOCK_DGRAM) is more like throwing a frisbee—fast and cheap, but no guarantees. Use TCP for chat apps, web servers, and anything where reliability matters. Use UDP for streaming video, online gaming, or DNS lookups.
To switch to UDP, just change SOCK_STREAM to SOCK_DGRAM:
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
No more accept() or listen()—with UDP, you just sendto() and recvfrom().
The Gotchas That Bite Beginners
Blocking calls will freeze your program. accept(), recv(), and connect() all block execution until something happens. If your client doesn't send data, your server waits forever. The fix is either threading (one thread per client) or setting sockets to non-blocking mode with socket.setblocking(False).
Ports can be sticky. If your server crashes, the OS may hold the port for minutes. You'll see OSError: Address already in use. Use server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) before bind() to bypass this.
Buffer sizes matter. recv(1024) means "give me up to 1024 bytes." If the client sends 2000 bytes, you only get the first chunk. You need to loop until you've received everything, or use a delimiter like \n to know when a message ends.
Making It Production-Ready
For real-world use, don't write your own socket server from scratch. Use asyncio for modern async I/O, or frameworks like Twisted, aiohttp, or FastAPI with WebSocket support. They handle threading, buffering, and error recovery so you don't have to.
But learning raw sockets first? That gives you the foundation to understand what those frameworks are doing under the hood. When you see await websocket.send(), you'll know it's just a fancy wrapper around socket.sendall().
The Bottom Line
Socket programming is the closest you'll get to the metal of the internet without leaving Python. It teaches you how data actually flows, what ports and addresses mean, and why your apps sometimes hang. Build a chat server, a file transfer tool, or a simple HTTP client—each one will cement these concepts.
And next time someone says "networking is hard," you can smile and write a 10-line server to prove them wrong.
Advertisement
Comments
Questions, corrections, and tips stay visible for everyone reading this page.
Join the discussion
No comments yet
Be the first to leave a note — it helps the next reader.