Computer Networking › Section B · The application layer › Topic B.9

Socket programming

Every protocol in this section is, in the end, a pair of programs exchanging bytes through sockets. Writing a tiny client and server yourself, first over UDP and then over TCP, shows exactly what each transport protocol does and does not do for an application.

What a socket program does

A client-server application is two programs: a server that waits at a known IP address and port, and a client that contacts it. Each creates a socket, the door between the program and the transport layer described in the topic "Principles of network applications". The Computer Science topic "A simple client-server program" built a first TCP example; here UDP is added and the two compared. The programmer chooses the transport when creating the socket. The examples below are Python 3, tested with Python 3.11 on one machine, so both programs use the loopback address 127.0.0.1, which always means this host. They use ports 50008 and 50007, above the well-known range 0 to 1023, which ordinary programs may not be allowed to use. Run each server in one terminal and its client in another.

Socket types in Python

Python's standard socket module wraps the operating system's sockets. The call socket(AF_INET, SOCK_DGRAM) creates a UDP socket, and socket(AF_INET, SOCK_STREAM) a TCP socket; AF_INET means IPv4, and AF_INET6 would mean IPv6. An address is a tuple of host and port, such as ("127.0.0.1", 50008). Sockets send and receive bytes, not text, so programs call .encode() on a string before sending and .decode() on the bytes received, which use UTF-8 by default. A server calls bind() to claim its port. A client usually does not, so the operating system gives it an ephemeral port the first time it sends.

A UDP server

This server sends back every message reversed. Line 1: from socket import socket, AF_INET, SOCK_DGRAM. Line 2: s = socket(AF_INET, SOCK_DGRAM). Line 3: s.bind(("127.0.0.1", 50008)). Line 4: while True: begins a loop that never ends. Line 5, indented: data, addr = s.recvfrom(2048). Line 6, indented: s.sendto(data.decode()[::-1].encode(), addr). recvfrom waits for one datagram of up to 2,048 bytes and returns its contents and the sender's address, a tuple of IP address and port. The slice [::-1] reverses the text. Because UDP has no connection, the server must name the destination, addr, on every sendto. One socket serves every client.

A UDP client

Line 1: from socket import socket, AF_INET, SOCK_DGRAM. Line 2: c = socket(AF_INET, SOCK_DGRAM). Line 3: c.settimeout(2). Line 4: c.sendto("network".encode(), ("127.0.0.1", 50008)). Line 5: reply, server = c.recvfrom(2048). Line 6: print(reply.decode()). Line 7: c.close(). With the server running, it prints krowten. There is no handshake: line 4 sends a datagram straight away. Line 3 matters because UDP gives no delivery guarantee. Without a timeout, a client whose request or reply was lost would wait for ever; with it, recvfrom raises an error after 2 seconds, and a real program would retry or give up.

Worked example: tracing the UDP exchange

Follow one run. 1. The server binds to port 50008 and blocks in recvfrom. 2. The client's sendto is its first use of the socket, so the operating system gives it an ephemeral port, say 61,204, and sends 7 bytes, the encoded word network, from that port to 127.0.0.1:50008. 3. The server's recvfrom returns those 7 bytes and addr = ("127.0.0.1", 61204). 4. It sends krowten back to that address. 5. The client's recvfrom returns the reply and the server's address, and it prints krowten. Check: if no server is running, nothing replies; depending on the operating system, the client either times out after 2 s or gets an error at once, but it never hangs.

A TCP server

This server replies with the number of words it receives. Line 1: from socket import socket, AF_INET, SOCK_STREAM. Line 2: s = socket(AF_INET, SOCK_STREAM). Line 3: s.bind(("127.0.0.1", 50007)). Line 4: s.listen(1). Line 5: while True:. Indented under it, line 6: conn, addr = s.accept(). Line 7: text = conn.recv(2048).decode(). Line 8: conn.sendall(str(len(text.split())).encode()). Line 9: conn.close(). listen turns s into a welcoming socket that waits for connection requests; its argument is the size of the queue of waiting clients. accept blocks until a client's handshake completes, then returns a brand-new connection socket, conn, for that client alone.

A TCP client

Line 1: from socket import socket, AF_INET, SOCK_STREAM. Line 2: c = socket(AF_INET, SOCK_STREAM). Line 3: c.connect(("127.0.0.1", 50007)). Line 4: c.sendall("sockets are doors".encode()). Line 5: print(c.recv(2048).decode()). Line 6: c.close(). With the server running, it prints 3. Unlike UDP, the client calls connect first, which performs TCP's three-way handshake; after that, sendall and recv need no address, because the connection already joins the two sockets. sendall keeps sending until every byte has gone. If no server is listening, connect fails with ConnectionRefusedError, because the other host rejects the handshake; Linux reports this at once, while Windows retries for about 2 s first.

Worked example: tracing the TCP exchange

1. The server's welcoming socket listens on port 50007. 2. The client's connect sends a connection request from an ephemeral port; once the handshake finishes, accept returns conn. 3. The client sends 17 bytes, the encoded phrase. 4. The server's recv returns them; split() gives the list sockets, are, doors, so len is 3, and the server sends the 1-byte string 3. 5. The client prints 3, and both sides close. Check: the welcoming socket s was never used for data. It goes back to accept and can admit the next client, while each conversation has its own connection socket.

Byte streams and many clients

TCP delivers a stream of bytes with no message boundaries. A recv call returns whatever has arrived, up to the size given, so a long message may come back in pieces, and two short ones may arrive joined. These examples rely on messages being short; real protocols mark where each message ends, as HTTP does with a blank line and a Content-Length header. UDP, by contrast, keeps each datagram whole or loses it entirely. The TCP server above also serves only one client at a time. Real servers handle many at once, for example by giving each connection socket its own thread, or with Python's socketserver or asyncio modules.

Common mistakes to avoid

First, sending a str instead of bytes; call .encode() first. Second, forgetting that a UDP client needs a timeout, or it may wait for ever for a lost reply. Third, reading data from the welcoming socket; a TCP server sends and receives on the socket that accept returns. Fourth, assuming one recv returns exactly one whole message over TCP. Fifth, calling sendto with an address on a connected TCP socket, or send without one on an unconnected UDP socket. Sixth, choosing a port another program already uses: bind then fails with an error saying the address is in use.

Key takeaways

A socket is created with a family and a type: AF_INET with SOCK_DGRAM for UDP, or SOCK_STREAM for TCP. Servers bind to a known address and port; clients get ephemeral ports. UDP programs use sendto and recvfrom, naming the address on every datagram, with no handshake, so clients need timeouts. TCP clients connect, which runs the handshake; servers listen on a welcoming socket and accept a new connection socket for each client, then use sendall and recv. Data travels as bytes, so encode and decode. TCP is a byte stream without message boundaries, so protocols must mark where messages end.

Flashcards

Flashcard

socket(AF_INET, SOCK_DGRAM)

Creates an IPv4 UDP socket

Datagrams, no connection.

Test your understanding

Question 1 of 5

While the reversing UDP server from the reading is running, a client sends the text stream. What does it receive?

Question 2 of 5

A client sends hello brave new world to the word-counting TCP server. What does the client print?

Question 3 of 5

In the TCP server, which socket carries the data exchanged with a particular client?

Question 4 of 5

Why does the UDP client call settimeout(2) before receiving?

Question 5 of 5

Which statement about the TCP client is correct?

← Previous topicNext topic →