Network Programming with sockets
A socket is an endpoint for sending and receiving bytes between programs over a network, and Python's socket module lets you build both the client and the server sides of that conversation.
Learn Network Programming with sockets in our free Python course — an interactive lesson with runnable examples, a practice exercise and a quick reference.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Almost every networked tool you use — web browsers, chat apps, databases — speaks over sockets underneath. We'll build a tiny TCP echo server and client on localhost, and use socketpair() for a clean, deterministic demo.
The cleanest way to see sockets in action is socket.socketpair() , which hands you two already-connected sockets — no IP, port, or server setup. Send bytes on one end, receive them on the other. Note .encode() and .decode() converting between strings and bytes:
Now the real thing. A server bind() s to an address, listen() s, and accept() s a connection; a client connect() s and exchanges data. We run the server in a thread, let it pick a free port (port 0 ), and use an Event so the client only connects once the server is ready — keeping it fast and deterministic:
The boundary between your Python strings and the network is always bytes. The pattern is simple and you'll repeat it constantly: .encode() before sendall , .decode() after recv :
Replace each ___ so a string is encoded, sent across a socket pair, received, and decoded back.
If the client runs before the server's listen() , the connection is refused. Use a synchronization signal like threading.Event (as in our demo) so the client waits until the server is ready.
Write a tiny server that receives a message and replies with it UPPERCASED. Run it in a thread, connect a client, send one message, and print the loud reply.
Lesson complete — you can talk over the network!
You understand TCP sockets, can create them with socket.socket , exchange data with sendall and recv , convert strings with encode / decode , build a tiny echo server and client over 127.0.0.1 , and reach for socketpair() for clean demos.
🚀 Up next: Checkpoint — put concurrency and I/O together in a build challenge.
Practice quiz
What is a socket, fundamentally?
- A function that formats strings for printing
- A type of Python dictionary for network data
- An endpoint for sending and receiving bytes between programs
- A file on disk used for logging
Answer: An endpoint for sending and receiving bytes between programs. A socket is one end of a network connection — programs create sockets and send bytes back and forth.
What kind of data do sockets actually transmit?
- bytes
- str objects
- JSON only
- Python lists
Answer: bytes. Sockets move raw bytes, which is why you encode strings before sending and decode after receiving.
Which method converts a str to bytes before sending?
- .decode()
- .bytes()
- .pack()
- .encode()
Answer: .encode(). Call .encode() to turn a string into bytes for sendall; use .decode() on received bytes to get a string back.
What does socket.socketpair() return?
- A single connected socket
- Two sockets already connected to each other
- A server socket and its address
- A tuple of (host, port)
Answer: Two sockets already connected to each other. socketpair() returns two already-connected sockets with no IP, port, or server setup — ideal for demos and tests.
What is the difference between send() and sendall()?
- sendall() keeps going until every byte is sent; send() may transmit only part
- send() is faster but encrypts the data
- They are identical aliases
- sendall() works only on socketpairs
Answer: sendall() keeps going until every byte is sent; send() may transmit only part. send() may send only part of the data and returns the count; sendall() loops until all bytes are sent.
In a TCP server, which call accepts an incoming client connection?
- connect()
- bind()
- accept()
- recv()
Answer: accept(). A server bind()s, listen()s, then accept()s a connection; the client connect()s to it.
What does binding a server to port 0 do?
- Disables the server
- Lets the operating system pick a free port
- Always uses port 80
- Raises an error
Answer: Lets the operating system pick a free port. Passing port 0 tells the OS to choose any available free port, which you can read via getsockname().
Why might a single recv() return only part of a large message?
- recv() always truncates to 8 bytes
- The socket is broken
- Only sendall() can fix the data
- TCP is a byte stream, not discrete packets
Answer: TCP is a byte stream, not discrete packets. TCP delivers a continuous stream, so production code loops on recv until it has a complete message.
What does sock.sendall("hello") (a str) raise?
- Nothing — it works fine
- A TypeError, because a bytes-like object is required
- A ConnectionError
- A ValueError about encoding
Answer: A TypeError, because a bytes-like object is required. sendall needs bytes; passing a str raises TypeError. Encode it first: sendall("hello".encode()).
In socket.socket(socket.AF_INET, socket.SOCK_STREAM), what does SOCK_STREAM select?
- A UDP datagram socket
- A raw socket
- A reliable TCP stream socket
- A Unix domain socket
Answer: A reliable TCP stream socket. SOCK_STREAM with AF_INET creates a TCP socket — a reliable, ordered byte stream.