Computer Science › Section E · Networking and the internet › Topic E.5
A simple client-server program
Every web browser, chat app and online game rests on the same small set of operations: a server waits on a port, a client connects, and the two exchange bytes. In this topic you build that pair yourself in a few lines of Python 3 and see how each line maps onto the layers you have just studied.
What we are building
The previous topics described clients, servers, ports and TCP in the abstract. Now we write them. Our server will wait for one client, read a short message, send it back in capital letters and close. Our client will connect, send a message and print the reply. Both programs run on the same computer, so you need no second machine and no special permissions, yet the data still passes through the full transport and network layers of the operating system. The code uses only Python's standard socket library and runs in Python 3 on Windows, macOS or Linux.
Sockets
A socket is the end point a program uses to talk to the network: the application layer hands data to a socket, and the operating system's transport layer does the rest. In Python, socket.socket(socket.AF_INET, socket.SOCK_STREAM) creates one. AF_INET chooses the IPv4 address family; SOCK_STREAM chooses a stream socket, which uses TCP. Choosing socket.SOCK_DGRAM instead gives a datagram socket, which uses UDP. An address is written as a pair, a tuple, of host and port, such as ("127.0.0.1", 5050).
Localhost and choosing a port
The address 127.0.0.1, also called localhost, is the loopback address: packets sent to it never leave the machine but go straight back up its own network stack. That makes it ideal for testing, and a server bound to it cannot be reached from other computers. For the port, pick a number from 1024 to 65,535 that no other program is using; we use 5050. Ports 0 to 1023 are reserved for well-known services, and on Linux an ordinary user usually cannot bind to them. Client and server must agree on the same host and port.
The server's steps
A TCP server follows a fixed pattern. It creates a socket, then calls bind with an address to claim that port from the operating system; if the port is already taken, bind raises an error. It calls listen to mark the socket as ready for incoming connections. It then calls accept, which waits until a client connects and returns two things: a new socket for talking to that one client, and the client's address. The original socket keeps listening for others. The server reads with recv, replies with sendall and finally closes both sockets.
The client's steps
A TCP client is shorter. It creates a socket and calls connect with the server's address. That single call makes the operating system perform TCP's three-way handshake and pick a temporary port for the client's end. If no program is listening at that address, connect fails with ConnectionRefusedError. Once connected, the client sends with sendall, which keeps sending until every byte has gone, then waits for the reply with recv. Finally it calls close, which ends the connection; the operating system frees the temporary port soon afterwards.
Worked example: an upper-case server
Save these statements, one per line, as server.py. 1. import socket loads the library. 2. srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) creates a TCP socket. 3. srv.bind(("127.0.0.1", 5050)) claims port 5050 on the loopback address. 4. srv.listen() starts listening. 5. conn, addr = srv.accept() waits for a client. 6. print("Connected by", addr) reports who connected. 7. data = conn.recv(1024) reads up to 1,024 bytes. 8. conn.sendall(data.upper()) replies in capitals. 9. conn.close() and then 10. srv.close() release both sockets. Check: there is exactly one accept, so this server handles one client and then exits.
Worked example: the client and a test run
Save as client.py: import socket, then cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM), then cli.connect(("127.0.0.1", 5050)), then cli.sendall("hello, server".encode("utf-8")), then reply = cli.recv(1024), then print(reply.decode("utf-8")), then cli.close(). 1. Start server.py in one terminal; it waits at accept. 2. Run client.py in a second terminal. 3. The server prints something like Connected by ('127.0.0.1', 54916); the port number varies, because the client's operating system chose it. 4. The client prints HELLO, SERVER and both programs exit. Check: running client.py with no server gives ConnectionRefusedError, because nothing is listening on port 5050.
Bytes, not text
Sockets carry bytes, not Python strings. Text must be encoded before sending, as in "hello, server".encode("utf-8"), and received bytes decoded with .decode("utf-8"). A literal written b"hello" is already bytes. TCP also delivers a stream of bytes with no message boundaries. recv(1024) returns at most 1,024 bytes, and it may return fewer than were sent, because the stream can arrive in pieces; it returns empty bytes, b"", when the other side has closed. Our short message arrives in one piece on one machine, but real protocols mark where each message ends, for example with a newline or a length at the front, and keep calling recv until the message is complete.
Worked example: the same idea over UDP
A UDP server has no listen, accept or connections. 1. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) creates a datagram socket. 2. s.bind(("127.0.0.1", 5051)) claims a port. 3. data, addr = s.recvfrom(1024) waits for one datagram and learns the sender's address. 4. s.sendto(data[::-1], addr) sends the bytes back reversed, then s.close(). The client creates its own SOCK_DGRAM socket, calls c.sendto(b"stressed", ("127.0.0.1", 5051)), then data, addr = c.recvfrom(1024), prints data.decode("utf-8") and closes. Check: the client prints desserts. Run the client first and its datagram is simply lost; depending on the operating system, recvfrom then waits forever or reports an error, but UDP never tries to send it again.
From demo to real server
A real server loops, accepting client after client, and often serves several at once using threads or similar tools. It must also treat every request as untrusted: check its length and content before acting on it, never run it as a command, and close connections that misbehave. Binding to 127.0.0.1 keeps a test server private; binding to "0.0.0.0" accepts connections on every network interface, so firewalls should block any port that does not need to be open. If a stopped server cannot restart because the address is still in use, setting srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) before bind usually lets it reclaim the port.
Common mistakes to avoid
First, starting the client before the server, which gives ConnectionRefusedError over TCP. Second, sending a str instead of bytes, which raises a TypeError; encode it first. Third, assuming one recv returns one whole message; TCP is a stream. Fourth, replying on the listening socket rather than the new socket that accept returned. Fifth, using a port below 1024 or one already in use. Sixth, letting the client and server disagree on the host or port. Seventh, exposing a test server to the network by binding to 0.0.0.0.
Key takeaways
A socket is a program's end point on the network. AF_INET with SOCK_STREAM gives a TCP socket; SOCK_DGRAM gives UDP. A TCP server calls bind, listen and accept, then recv and sendall on the socket that accept returns; a TCP client calls connect, which triggers the handshake. Use 127.0.0.1 and a free port from 1024 to 65,535 for testing. Sockets send bytes, so encode and decode text, and remember that recv may return less than a whole message. UDP uses sendto and recvfrom with no connection. Real servers loop, validate every request and expose only the ports they need.
Flashcards
Flashcard
A program's end point for sending and receiving over the network
Test your understanding
Question 1 of 5
Which sequence of socket calls does a simple TCP server make, after creating its socket, to receive its first client?
Question 2 of 5
What does socket.SOCK_STREAM select when a socket is created?
Question 3 of 5
A student runs the TCP client before starting the server. What happens?
Question 4 of 5
Why does the client call "hello, server".encode("utf-8") before sending?
Question 5 of 5
A server calls data = conn.recv(1024). Which statement is correct?
