Client-Server Programming
In questa pagina 5
This note frames the client-server model from the point of view of someone who has to program a network application: where the program ends and the operating system begins, how data are encapsulated, what a port identifies. The actual socket calls and code are in Socket ProgrammingA socket is a communication endpoint identified like a file descriptor; a TCP server runs socket, setsockopt, bind, listen, accept, read/write, close, while the client runs socket, connect, read/write, close.Socket Programming →; the TCP and UDP services behind them are in TCP - Connection, Reliability and Flow ControlTCP is the connection-oriented, reliable transport protocol that turns IP's unreliable service into an ordered byte stream without errors or duplicates; the connection opens with a three-way handshake (SYN, SYN+ACK, ACK) and closes with FIN segments, bytes are numbered (sequence number = first byte of the segment, cumulative ACK = next byte expected), the sender may transmit min(rwnd, cwnd) unacknowledged bytes (rwnd, the receiver window in a 16-bit field, is flow control), errors are handled with checksum, ACKs, retransmission timeout and fast retransmit after three duplicate ACKs, and to fill the pipe the window must reach the bandwidth-delay product, with maximum throughput MSS times Wmax over RTT.TCP - Connection, Reliability and Flow Control → and UDP - User Datagram ProtocolUDP is the connectionless, unreliable transport protocol that adds to IP only process-to-process communication through ports and an optional checksum; its header is 8 bytes (source port, destination port, length, checksum), the checksum covers a pseudo-header (IP addresses, protocol 17, length), the UDP header and the data as a one's complement sum (0 means not computed and a computed 0 is sent as 0xFFFF), and UDP has no connection setup, sequence numbers, flow, error or congestion control, which makes it suitable for short messages (DNS, DHCP, RIP, SNMP) and real-time applications.UDP - User Datagram Protocol →.
Layers and the TCP/IP stack
The ISO/OSI model (ISO, 1984) is a reference model, not a protocol: it describes in seven layers the functions needed to make systems from different manufacturers communicate. The TCP/IP stack is the real architecture of the Internet and has four layers (see ISO-OSI Model and TCP-IP StackCommunication between two computers is too varied a problem (signals, errors, medium access, routing, flow control, data representation) for a single protocol, so it is divided into layers. The ISO/OSI model has 7 layers (physical, data link, network, transport, session, presentation, application); the TCP/IP stack merges the top three into one application layer, so it has 5. Each layer offers a service to the one above and talks only to its peer layer through PDUs; going down a header (PCI) is added: encapsulation. Addresses: MAC (link, local), IP (network, global), port (transport).ISO-OSI Model and TCP-IP Stack →).
| OSI | name | PDU | examples | TCP/IP |
|---|---|---|---|---|
| 7 | application | message | HTTP, DNS, SMTP | application |
| 6 | presentation | message | TLS, character encoding, JPEG | (inside the application) |
| 5 | session | message | RPC, recovery points | (inside the application) |
| 4 | transport | segment (TCP), datagram (UDP) | TCP, UDP, QUIC | transport |
| 3 | network | packet | IP, ICMP | internet |
| 2 | data link | frame | Ethernet, Wi-Fi | network access |
| 1 | physical | bits | cable, fibre, radio | network access |
In practice layers 5, 6 and 7 collapse into a single application layer: HTTP itself decides how to structure messages, how to encrypt them (using TLS below it) and how to resume a transfer.
Where our program sits
An important point: which layers run in our program and which in the kernel.
+--------------------------------------+
| C program: HTTP client or server | layers 5-7: we write the message syntax
+--------------------------------------+
| socket API (system calls) | <-- user space / kernel boundary
+--------------------------------------+
| TCP or UDP | layer 4 |
| IP | layer 3 | in the kernel
| NIC driver, Ethernet/Wi-Fi | layers 1-2|
+--------------------------------------+When we write an HTTP client in C we build the strings GET / HTTP/1.1\r\n... ourselves and hand them to the kernel with write; segmentation, retransmissions, routing and framing are done below, and we only see a reliable byte stream. This also explains why a read can return fewer bytes than needed: layer 4 delivered what had arrived, not "one HTTP message".
PDU, SDU and encapsulation
Definition (PDU and SDU). The PDU (Protocol Data Unit) is the unit of data exchanged between two entities of the same layer on different systems: protocol header plus data. The SDU (Service Data Unit) is the block of data that a layer receives from the upper layer, to be carried as is. , and the PDU of layer becomes the SDU of layer .
On transmission each layer adds its own header (layer 2 also a trailer): this is encapsulation. On reception each layer strips its header and passes the rest up (decapsulation).
Example. An HTTP request of 51 bytes crosses the stack of a client:
GET /index.html HTTP/1.1
Host: www.example.com| layer | operation | size |
|---|---|---|
| application | SDU = HTTP request: GET /index.html HTTP/1.1\r\n (26 bytes) + Host: www.example.com\r\n (23) + empty line \r\n (2) |
51 bytes |
| transport | TCP adds the header (20 bytes without options): ports, sequence number, window, checksum | segment of 71 bytes |
| network | IPv4 adds 20 bytes: IP addresses, TTL, protocol = 6 | packet of 91 bytes |
| data link | Ethernet adds 14 bytes of header (destination and source MAC, EtherType 0x0800) and 4 of CRC |
frame of 109 bytes |
| physical | the frame becomes a bit sequence | 109 bytes = 872 bits (plus preamble) |
The ratio between useful data and transmitted bytes is : with small requests header overhead is high. The 91-byte packet is far smaller than the Ethernet MTU (1500 bytes), so there is no fragmentation.
SAP: the service access point
Definition (SAP). A SAP (Service Access Point) is the point where a layer offers its services to the layer above: the logical interface between two adjacent layers. Every SAP has an address that says to which user of the service the data must be delivered.
The same mechanism recurs at every layer, with a different name for the SAP address:
| layer that delivers | field identifying the SAP | example values | towards |
|---|---|---|---|
| Ethernet (2) | EtherType | 0x0800 IPv4, 0x86DD IPv6, 0x0806 ARP |
the network protocol |
| IP (3) | protocol field | 1 ICMP, 6 TCP, 17 UDP | the transport protocol |
| TCP or UDP (4) | port number | 80 HTTP, 443 HTTPS, 53 DNS | the application process |
Demultiplexing at the receiver is a chain of SAPs: the frame has EtherType 0x0800, so it goes to IP; the packet has protocol 6, so it goes to TCP; the segment has destination port 80, so it goes to the process that did bind on port 80. For a C program the SAP of the transport layer is the socket API: the SAP address is the pair (IP address, port), and the descriptor returned by socket() is our local reference to that access point. A server that calls bind on port 8080 is registering its SAP: from then on segments with destination port 8080 are delivered to it.
In the formal OSI model, interaction through a SAP uses four service primitives: request (the upper layer asks for the service), indication (the lower layer notifies the remote user), response and confirm. In a network program they are recognisable: connect is a request, the return of accept on the server is the corresponding indication.
Communication models
Client/server
Two roles: the client opens the communication and sends a request, the server is always listening, processes and replies. The model works like a function call: the caller sends arguments and waits for the result. It is the model of HTTP, DNS, SMTP: the server has a known address (DNS name and port), the client does not.
- Advantages: data and rules are centralised, control and security are simpler, the client can be minimal.
- Limits: the server is a single point of failure; scalability is limited by its capacity; if it is overloaded latency grows.
- Remedies: several servers behind a load balancer, caches and proxies, replication.
Servers can be iterative (one client at a time) or concurrent (several clients together, with processes, threads or events).
Peer-to-peer
All nodes (peers) are equal: each is client and server at once and talks directly to the others, with no central node. Examples: BitTorrent, blockchain networks. Advantages: scalability (each new node also brings capacity), resilience to failures, distributed bandwidth. Disadvantages: peer discovery and link management are complex, security and authentication are hard, performance depends on the available peers.
Publish/subscribe/notify
Three roles: the publisher produces data, the subscriber subscribes to receive it, the broker is the intermediary that records subscriptions and forwards each published event to those interested. This model is developed in Internet of Things, Publish-Subscribe and MQTTThe Internet of Things connects constrained embedded devices (microcontrollers with kilobytes of RAM, IETF classes 0, 1 and 2) organised in edge, fog, core and cloud levels; the publish/subscribe model, used by MQTT, lets a broker forward events from publishers to subscribers, which are decoupled in space, time and synchronisation, and topics are selected with the wildcards plus (one level) and hash (all remaining levels).Internet of Things, Publish-Subscribe and MQTT →.
| client/server | peer-to-peer | publish/subscribe | |
|---|---|---|---|
| communication | request, then reply | direct between peers | event, forwarded by the broker |
| who starts | the client | anyone | the publisher (data), the subscriber (subscription) |
| coupling | strong (the client knows the server) | strong between peers | weak |
| critical point | server | peer discovery | broker |
| example | HTTP | BitTorrent | app notifications, MQTT |
HTTP is client/server by construction: the server cannot "push" data if the client has not asked. To obtain notifications one uses polling or long polling, or WebSocket, which opens a persistent bidirectional channel on which the server can send events whenever it wants.
Typical mistakes
- Confusing PDU and SDU: the SDU of layer is the PDU of layer , without the layer- header.
- Saying that OSI is "the protocol used on the Internet": it is a reference model; the Internet uses TCP/IP.
- Placing the transport layer in the application program: TCP and UDP are in the kernel, the program uses them through the socket API.
- Confusing port and IP address: the IP identifies the machine, the port identifies the process (the transport SAP is the pair).
- Saying that client/server and publish/subscribe are equivalent: in the first the client asks and waits, in the second the subscriber subscribes and receives asynchronous notifications.
Versione ripasso
- Models. ISO/OSI (1984): 7 layers, reference model. TCP/IP: 4 layers (network access, internet, transport, application), the real architecture; 5, 6 and 7 collapse into the application. PDU: message (7-5), segment (TCP) or datagram (UDP) (4), packet (3), frame (2), bits (1).
- Where the program sits. The C program writes the message syntax (layers 5-7); TCP/UDP, IP and drivers are in the kernel; the boundary is the socket API (Socket ProgrammingA socket is a communication endpoint identified like a file descriptor; a TCP server runs socket, setsockopt, bind, listen, accept, read/write, close, while the client runs socket, connect, read/write, close.Socket Programming →). A
readreturns what transport delivered, not "a message". - PDU and SDU. ; the PDU of layer is the SDU of layer . Encapsulation on transmission, decapsulation on reception.
- Example. HTTP request of 51 bytes: TCP segment 71 (+20), IP packet 91 (+20), Ethernet frame 109 (+14 and +4 CRC). Efficiency ; no fragmentation (91 < MTU 1500).
- SAP. Interface between adjacent layers, with an address: EtherType (
0x0800IPv4,0x86DDIPv6,0x0806ARP) for Ethernet; protocol field (6 TCP, 17 UDP, 1 ICMP) for IP; port for TCP/UDP. Demultiplexing chain: EtherType, protocol, port. Transport SAP for a C program = socket API, address = (IP, port). - OSI primitives: request, indication, response, confirm (
connect= request,accept= indication). - Client/server. The client asks and waits, the server is always listening: like a function call. Limits: single point of failure, scalability, latency under load; remedies: load balancers, caches, replication. Servers iterative or concurrent.
- Peer-to-peer. Equal nodes, direct communication (BitTorrent). Pros: scalability, resilience; cons: complex management, security, variable performance.
- Publish/subscribe/notify. Publisher, subscriber, broker (Internet of Things, Publish-Subscribe and MQTTThe Internet of Things connects constrained embedded devices (microcontrollers with kilobytes of RAM, IETF classes 0, 1 and 2) organised in edge, fog, core and cloud levels; the publish/subscribe model, used by MQTT, lets a broker forward events from publishers to subscribers, which are decoupled in space, time and synchronisation, and topics are selected with the wildcards plus (one level) and hash (all remaining levels).Internet of Things, Publish-Subscribe and MQTT →).
- Comparison: client/server = request and reply, strong coupling, critical point the server (HTTP); peer-to-peer = direct, critical point peer discovery (BitTorrent); publish/subscribe = events forwarded by the broker, weak coupling, critical point the broker (MQTT).
- HTTP is client/server: the server cannot push; notifications need polling, long polling or WebSocket.
- Typical mistakes: PDU vs SDU; OSI as the Internet protocol; TCP inside the program instead of the kernel; port vs IP address; client/server equated with publish/subscribe.