本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 2 · 本科二年级
16Sockets
Two programs on one laptop, no cable between them, and still a conversation:
$ gcc -std=c17 -O2 -Wall -Wextra -o echo_pair echo_pair.c -lm && ./echo_pair
server: a client on 127.0.0.1 sent 13 bytes
client: received 13 bytes: hello, server
The client sent 13 bytes; the server received them, saw that they came from the address 127.0.0.1, and sent them back. The bytes went down through the operating system’s network code and came back up, exactly as they would between two machines on two continents, except that they never left this one. The tool is the socket, a file descriptor for a conversation over the network. This chapter writes clients and servers with sockets, shows the two traps every network program meets (a stream has no message boundaries; a number has a byte order), serves many clients at once in three ways, and measures them.
You already know
Book 2: a web browser is a client that sends requests to a server, which answers; a machine on a network has an address, and a port number names one program on it, so that one machine can run several servers. Book 3, ch. 6: the byte order of a machine says in which order the bytes of a number lie in memory. Chapter 14: descriptors, read and write, and end of file on a pipe. Chapter 15: threads, locks, and the cost of a thread.
16.1 The socket interface
Definition 16.1 (Socket, socket address)
A socket is an endpoint of communication, created by socket(domain, type, 0), which returns a file descriptor. A socket address names an endpoint: for the Internet domain (AF_INET), an IP address and a port number, held in a struct sockaddr_in.
Definition 16.2 (Port number)
A port number is a 16-bit number that tells the endpoints of one machine apart: the system delivers each arriving segment or datagram to the socket bound to its destination address and port.
Definition 16.3 (Stream socket, datagram socket)
A stream socket (SOCK_STREAM, the TCP protocol) carries a reliable, ordered sequence of bytes between two connected endpoints; a datagram socket (SOCK_DGRAM, the UDP protocol) carries separate messages, each addressed on its own.
Definition 16.4 (Loopback address)
A loopback address is an address of the block 127.0.0.0/8, usually 127.0.0.1: a packet sent to it never leaves the machine.
Every program of this chapter uses it, so nothing it does is visible from outside. The transport chapter (Chapter 19) explains what TCP and UDP do underneath; here we use them.
A server and a client make different calls, in a fixed order:
Method 16.5 (A TCP server and client)
Server: socket; bind it to its address and port; listen, which turns it into a listening socket; then repeatedly accept, which waits for a client and returns a new socket for that connection; recv and send on that socket; close it. Client: socket; connect to the server’s address and port (the system picks the client’s own port); send and recv; close. Every call returns on failure, which a real program checks.
Definition 16.6 (Listening socket, connected socket)
A listening socket is a stream socket on which listen was called: it carries no data, only connection requests, and accept turns each request into a connected socket, one per client, which carries that connection’s bytes.
int main(void)
{
int lfd = socket(AF_INET, SOCK_STREAM, 0); /* 1. a socket */
int one = 1;
setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
struct sockaddr_in me = {0};
me.sin_family = AF_INET;
me.sin_port = htons(PORT);
me.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (bind(lfd, (struct sockaddr *)&me, sizeof me) != 0) { /* 2. an address */
perror("bind");
return 1;
}
listen(lfd, 16); /* 3. accept connections */
if (fork() == 0) {
close(lfd);
client();
exit(0); /* flushes stdout */
}
server(lfd);
wait(NULL);
close(lfd);
return 0;
}
listen; the client runs in a child process code/bachelor-2/16-sockets/listings/echo_pair.cstatic void client(void)
{
int fd = socket(AF_INET, SOCK_STREAM, 0); /* 1. a socket */
struct sockaddr_in srv = {0};
srv.sin_family = AF_INET;
srv.sin_port = htons(PORT);
inet_pton(AF_INET, "127.0.0.1", &srv.sin_addr);
connect(fd, (struct sockaddr *)&srv, sizeof srv); /* 2. to the server */
send(fd, "hello, server", 13, 0);
char buf[64];
ssize_t n = recv(fd, buf, sizeof buf, 0);
printf("client: received %zd bytes: %.*s\n", n, (int)n, buf);
close(fd);
}
static void server(int lfd)
{
struct sockaddr_in peer;
socklen_t len = sizeof peer;
int c = accept(lfd, (struct sockaddr *)&peer, &len); /* 4. one connection */
char buf[64];
ssize_t n = recv(c, buf, sizeof buf, 0);
printf("server: a client on %s sent %zd bytes\n", inet_ntoa(peer.sin_addr), n);
fflush(stdout);
send(c, buf, n, 0); /* echo them back */
close(c);
}
accept returns when a client’s connect arrives; the data then flows on the new socket, while the listening one can wait for the next client.The client is forked after listen, so its connect cannot arrive before the server is ready. The server prints and flushes before it answers, and the client prints only after the answer arrives, which fixes the order of the two lines in Output 16.1.
16.2 Streams have no message boundaries
The client sent 13 bytes in one send, and the server received 13 bytes in one recv. That was luck. A stream socket carries bytes, not messages: the receiver gets the bytes in order, but a recv may return any number of them, from one to all that have arrived.
$ gcc -std=c17 -O2 -Wall -Wextra -o partial_recv partial_recv.c net.c -lm && ./partial_recv
sender: one send call returned 1048576
receiver: 1048576 bytes in all
the first recv returned less than all: yes
more than one recv call: yes
send of 1 MiB, received by several recv calls.$ gcc -std=c17 -O2 -Wall -Wextra -o boundaries boundaries.c net.c -lm && ./boundaries
TCP: recv returned 8 bytes: abcdefgh
UDP: recvfrom returned 2 bytes: ab
UDP: recvfrom returned 2 bytes: cd
UDP: recvfrom returned 4 bytes: efgh
Over TCP, the three sends “ab”, “cd” and “efgh” arrive as eight bytes that one recv returns together; it could as well have returned them in five pieces. Over UDP, each sendto is one datagram, and each recvfrom returns exactly one. A datagram can be lost, though, and one longer than the buffer is cut (Exercise 16.5); TCP loses nothing and keeps the order, but leaves the boundaries to the program.
So a program that needs bytes must loop:
ssize_t recv_all(int fd, void *buf, size_t n)
{
size_t got = 0;
while (got < n) {
ssize_t k = recv(fd, (char *)buf + got, n - got, 0);
if (k < 0)
return -1;
if (k == 0)
break; /* end of stream */
got += k;
}
return got;
}
Proposition 16.7 (Receiving everything)
If no call fails, recv_all(fd, buf, n) returns with the next bytes of the stream in buf, or, if the stream ends first, returns the number of bytes that remained, with those bytes in buf.
Proof. The loop keeps the invariant: buf[0..got) holds the next got bytes of the stream, in order, and . It holds at the start (). A recv that returns copies the next bytes, at most of them, to buf + got, and got grows by : the invariant still holds. Each turn either increases got or ends the loop, so the loop ends: either , or recv returned 0, which on a stream means that the other side has closed and no byte remains. ∎
send has the same weakness in the other direction: it may accept fewer bytes than given, and send_all loops in the same way.
16.3 Byte order and framing
Numbers on the network have a byte order too.
Definition 16.8 (Network byte order)
Network byte order is big-endian: the Internet protocols send every number of a header with its most significant byte first.
This laptop is little-endian, so every number that goes into a protocol header or a message must be converted: htons and htonl (host to network, short and long) and ntohs, ntohl back.
$ gcc -std=c17 -O2 -Wall -Wextra -o byteorder byteorder.c -lm && ./byteorder
0x0a0b0c0d in memory: 0d 0c 0b 0a
htonl(0x0a0b0c0d): 0a 0b 0c 0d
port 44160 in memory: 80 ac
htons(44160): ac 80
ntohs(htons(44160)) = 44160
A port number goes into sin_port in network order. Forgetting htons does not fail: the server listens on the port whose bytes are those of 44164 reversed, and the client, which asks for 44164, finds nobody:
$ gcc -std=c17 -O2 -Wall -Wextra -o wrong_port wrong_port.c -lm && ./wrong_port
asked for port 44164, listening on port 33964
client: connect to 44164: Connection refused
htons (Exercise 16.2).Since the stream does not keep message boundaries, a protocol must mark them itself. There are two ways. A delimiter ends each message, as the newline ends a line in many text protocols; the message must then never contain the delimiter, or must escape it. A length prefix puts the length first; the message may then contain anything.
Definition 16.9 (Length-prefixed framing)
In length-prefixed framing, a message of bytes is sent as 4 bytes holding in network byte order, followed by the bytes. Decoding a buffer reads 4 bytes as a length , then takes the next bytes as the message, and starts again after it.
size_t frame(char *out, const char *msg, uint32_t n)
{
uint32_t len = htonl(n); /* the length, big-endian */
memcpy(out, &len, 4);
memcpy(out + 4, msg, n);
return 4 + (size_t)n;
}
size_t unframe(const char *in, size_t len, const char **msg, uint32_t *n)
{
if (len < 4)
return 0; /* not even a whole length */
uint32_t be;
memcpy(&be, in, 4);
*n = ntohl(be);
if (len - 4 < *n)
return 0; /* the message is not all there */
*msg = in + 4;
return 4 + (size_t)*n;
}
who 1 framed, byte by byte (offsets above): the length 5 in four big-endian bytes, then the five bytes of the message. The receiver reads the four bytes, then exactly five more; whatever follows is the next message.Proposition 16.10 (Unique decoding)
Let be the concatenation of the framings of messages . Decoding from its first byte yields exactly , in that order, and uses all of .
The proof, by induction on , is Exercise 16.8. A delimiter gives the same guarantee only if no message contains it.
16.4 A directory service
The town keeps its people and streets in two tables. A small service answers two requests over TCP, each framed as above: who 7 gives a person’s name, year of birth and street; street Mill Lane counts the people who live there. Every connection carries one request and one answer. The client is a short Python program, whose struct.pack("!I", n) writes in four big-endian bytes (the ! is network order):
def recv_all(sock, n):
data = b""
while len(data) < n: # recv may return part of n
part = sock.recv(n - len(data))
if not part:
raise ConnectionError("the server closed the connection early")
data += part
return data
def ask(port, request):
with socket.create_connection(("127.0.0.1", port)) as sock:
body = request.encode()
sock.sendall(struct.pack("!I", len(body)) + body) # !I: 4 bytes, big-endian
(n,) = struct.unpack("!I", recv_all(sock, 4))
return recv_all(sock, n).decode()
$ gcc -std=c17 -O2 -Wall -Wextra -o directory_server *.c
$ ./directory_server 44166 poll 4 &
$ python3 directory_client.py 44166 "who 1" "who 4" "street Bridge Road" "where is 7"
'who 1' -> Emil Thornworth, born 1967, Bridge Road
'who 4' -> Sami Ashworth, born 2002, Orchard Way
'street Bridge Road' -> Bridge Road: 8 people
'where is 7' -> error: unknown request
$ wait
The server’s & runs it in the background; it serves four connections and ends, and wait waits for it. A C server and a Python client agree because the protocol fixes every byte: the length’s size and order, the text’s encoding. Neither side’s language matters.
16.5 Many clients at once
A server that handles one client from accept to close makes every other client wait, even when the first is slow to send. The calls it makes wait.
Definition 16.11 (Blocking call, non-blocking descriptor)
A blocking call waits until it can complete: accept until a client connects, recv until a byte has arrived. On a descriptor made non-blocking (flag O_NONBLOCK), the same calls return at once with the error EAGAIN instead of waiting.
There are three classic ways to serve several clients at once.
void serve_fork(int lfd, long connections)
{
for (long k = 0; k < connections; k++) {
int c = accept(lfd, NULL, NULL);
if (fork() == 0) { /* the child serves ... */
close(lfd);
handle(c);
_exit(0);
}
close(c); /* ... the parent goes back to accept */
while (waitpid(-1, NULL, WNOHANG) > 0)
; /* reap the children that are done */
}
while (wait(NULL) > 0)
;
}
The child inherits the connected socket and the parent closes its copy (the connection ends only when both have, as for a pipe). The children are reaped as they end. A thread per connection is lighter, since a thread shares the process’s memory and is cheaper to start:
void serve_threads(int lfd, long connections)
{
atomic_store(&finished, 0);
for (long k = 0; k < connections; k++) {
int c = accept(lfd, NULL, NULL);
pthread_t t;
pthread_create(&t, NULL, handle_thread, (void *)(intptr_t)c);
pthread_detach(t); /* nobody joins it: it cleans up alone */
}
while (atomic_load(&finished) < connections)
sched_yield(); /* let the last threads finish */
}
Definition 16.12 (Event loop)
An event loop serves many connections from one thread: it asks the system, with poll(fds, n, timeout), which of a set of descriptors are ready (a recv or an accept on them would not wait), handles each ready one briefly, and asks again. A connection’s state between two events, such as a request received in part, is kept in a structure of the program.
void serve_poll(int lfd, long connections)
{
static struct pollfd p[MAXC + 1];
static struct conn st[MAXC + 1];
int n = 1;
long accepted = 0, done = 0;
p[0] = (struct pollfd){.fd = lfd, .events = POLLIN};
while (done < connections) {
poll(p, n, -1); /* sleep until some descriptor is ready */
if ((p[0].revents & POLLIN) && accepted < connections && n <= MAXC) {
int c = accept(lfd, NULL, NULL); /* a new connection: watch it too */
p[n] = (struct pollfd){.fd = c, .events = POLLIN};
st[n] = (struct conn){.fd = c};
n++, accepted++;
}
for (int i = n - 1; i >= 1; i--) {
if (!(p[i].revents & (POLLIN | POLLHUP)))
continue;
struct conn *s = &st[i];
ssize_t k = recv(s->fd, s->buf + s->len, sizeof s->buf - s->len, 0);
const char *msg;
uint32_t len;
if (k > 0)
s->len += k;
if (k > 0 && !unframe(s->buf, s->len, &msg, &len) && s->len < sizeof s->buf)
continue; /* request not complete yet: wait */
if (k > 0 && unframe(s->buf, s->len, &msg, &len)) {
char reply[256];
send_msg(s->fd, reply, directory_answer(msg, len, reply, sizeof reply));
}
close(s->fd); /* answered, or broken: forget it */
p[i] = p[n - 1], st[i] = st[n - 1];
n--, done++;
}
}
}
poll, every connection’s state in st code/bachelor-2/16-sockets/listings/servers.cpoll. Nothing blocks, so one thread keeps every connection moving.Which is fastest? loadtest.c starts each server in a child process and sends it 4000 connections from 8 client threads, each connection with one request:
$ gcc -std=c17 -O2 -Wall -Wextra -o loadtest *.c
$ ./loadtest
design seconds requests/s
process per connection 1.092 3662
thread per connection 0.546 7331
event loop (poll) 0.366 10917
failed requests: 0
fork, a thread, or nothing extra; with one short request per connection, that cost is most of the work.The order follows what each design pays per connection: a process (the copy of the page tables, the exit, the reaping), a thread (a stack and a scheduling entry), or an entry in an array. With long connections that carry many requests, the gap narrows; with thousands of idle connections, an event loop needs no thread for each, which is why busy servers are built on it (Exercise 16.11). Its weakness is that one slow handler stops every client: a handler must never wait.
In practice — Ports and restarts
A server restarted at once often fails with “Address already in use”: its old connections linger for a while in the TIME_WAIT state, to absorb late packets. The option SO_REUSEADDR, set before bind, allows the bind anyway, and every server of this chapter sets it (Exercise 16.12). Ports below 1024 are reserved to privileged programs; servers under test use high ports.
Facts as of 2026
On Linux, a client’s own port is chosen from 32 768 to 60 999 by default; the load test’s 12 000 short connections borrow a good share of them for a minute.
16.6 Exercises
Exercise 16.1 ★
A server sends “ab”, then “cd”, then closes. The client reads with a buffer of 3 bytes and prints each piece in brackets. List every output it may print.
void server_side(int c)
{
send(c, "ab", 2, 0);
send(c, "cd", 2, 0);
close(c);
}
void client_side(int fd)
{
char buf[3];
ssize_t n;
while ((n = recv(fd, buf, sizeof buf, 0)) > 0)
printf("[%.*s]", (int)n, buf);
printf("\n");
}
Solution
Solution of Exercise 16.1.
The client receives the bytes abcd in order, cut anywhere into pieces of at most 3 bytes, each a nonempty prefix of what is left. The possible outputs are the compositions of 4 into parts of at most 3: [abc][d], [a][bcd], [ab][cd], [ab][c][d], [a][bc][d], [a][b][cd] and [a][b][c][d], 7 outputs. The two sends do not force a cut between b and c: [abc][d] happens if both had arrived before the first recv.
Exercise 16.2 ★
In wrong_port.c, compute the port the server really listens on, from the bytes of 44164, and explain why bind succeeded.
Solution
Solution of Exercise 16.2.
. Stored without htons on this little-endian machine, sin_port holds the bytes 84 ac; the system reads them as a big-endian port, , as getsockname reports. bind succeeded because 33 964 is an ordinary free port: nothing checks that it is the one meant. On a big-endian machine the bug would be invisible, as htons does nothing there; that is why the conversion must be written even where it is not needed.
Exercise 16.3 ★
Write recv_all(fd, buf, n) as specified by Proposition 16.7, and send_all.
Solution
Solution of Exercise 16.3.
int send_all(int fd, const void *buf, size_t n)
{
const char *p = buf;
while (n > 0) {
ssize_t k = send(fd, p, n, MSG_NOSIGNAL); /* EPIPE instead of SIGPIPE */
if (k <= 0)
return -1;
p += k, n -= k;
}
return 0;
}
recv_all is Listing 16.3, proved by Proposition 16.7. send_all loops the same way: send may accept fewer bytes than given (when the socket’s send buffer is nearly full), so the rest is sent again from where it stopped. MSG_NOSIGNAL turns the SIGPIPE of a write to a closed connection into an error return. The test sends a frame and lines one byte at a time and checks that they arrive whole.
Exercise 16.4 ★
Write in hexadecimal the bytes on the wire for the framed request street Mill Lane. How many bytes does a recv_msg read, in how many calls to recv_all?
Solution
Solution of Exercise 16.4.
street Mill Lane has 16 bytes, so the length is 00 00 00 10, followed by 73 74 72 65 65 74 20 4d 69 6c 6c 20 4c 61 6e 65: 20 bytes in all. recv_msg reads them in two calls to recv_all, one for the 4 bytes of the length and one for the 16 of the message; each of those may make several recv calls.
Exercise 16.5 ★★
What does this program print, and why? What happens to the other 90 bytes?
memset(big, 'x', sizeof big);
sendto(fd, big, sizeof big, 0, (struct sockaddr *)&me, sizeof me); /* to itself */
sendto(fd, "next", 4, 0, (struct sockaddr *)&me, sizeof me);
char buf[10];
ssize_t n = recvfrom(fd, buf, sizeof buf, 0, NULL, NULL);
printf("first recvfrom: %zd bytes\n", n);
n = recvfrom(fd, buf, sizeof buf, 0, NULL, NULL);
printf("second recvfrom: %zd bytes: %.*s\n", n, (int)n, buf);
Solution
Solution of Exercise 16.5.
$ gcc -std=c17 -O2 -Wall -Wextra -o exo_truncate exo_truncate.c -lm && ./exo_truncate
first recvfrom: 10 bytes
second recvfrom: 4 bytes: next
A recvfrom returns one datagram. When it is larger than the buffer, the first 10 bytes are copied and the other 90 are discarded with the datagram: they are not kept for the next call, which returns the next datagram, next. A program that cares passes MSG_TRUNC, with which Linux returns the datagram’s real length, or uses a buffer as large as the largest datagram its protocol allows.
Exercise 16.6 ★★
This echo server spins after its client leaves. Explain the output and fix the loop.
while (calls < 1000000) { /* the bug is inside; this guard is not */
ssize_t n = recv(c, buf, sizeof buf, 0);
calls++;
zeros += n == 0;
send(c, buf, n > 0 ? n : 0, MSG_NOSIGNAL);
}
$ gcc -std=c17 -O2 -Wall -Wextra -o exo_loop exo_loop.c net.c -lm && ./exo_loop
1000000 calls to recv, 999999 of them returned 0
Solution
Solution of Exercise 16.6.
After hello and its echo, the client closes. Every later recv returns 0 at once, end of stream, and the loop goes round without waiting: 999 999 calls in a fraction of a second, all returning 0, burning a processor. Without the guard it would never stop. The fix is to leave the loop on 0 and on : while ((n = recv(c, buf, sizeof buf, 0)) > 0) send_all(c, buf, n);, then close(c). Sending back n bytes when n is would be a second bug, which the guard’s n > 0 ? n : 0 hides.
Exercise 16.7 ★★
Write a line reader, lr_line(r, out, cap), that returns the next line of a stream without its newline, using a buffer of its own so that it calls recv with large sizes and never reads past what it needs to keep.
Solution
Solution of Exercise 16.7.
ssize_t lr_line(struct linereader *r, char *out, size_t cap)
{
for (;;) {
char *nl = memchr(r->buf + r->start, '\n', r->end - r->start);
if (nl) { /* a whole line is buffered */
size_t n = nl - (r->buf + r->start);
size_t k = n < cap - 1 ? n : cap - 1; /* a longer line is cut */
memcpy(out, r->buf + r->start, k);
out[k] = '\0';
r->start += n + 1;
return k;
}
if (r->start > 0) { /* make room: move the rest down */
memmove(r->buf, r->buf + r->start, r->end - r->start);
r->end -= r->start;
r->start = 0;
}
if (r->end == sizeof r->buf)
r->end = 0; /* no newline in 4096 bytes: drop them */
ssize_t k = recv(r->fd, r->buf + r->end, sizeof r->buf - r->end, 0);
if (k <= 0)
return -1; /* end (a last partial line is lost) */
r->end += k;
}
}
The unread bytes live in buf[start..end). If they contain a newline, the line is returned and start moves past it, keeping the bytes after it for the next call: one recv may bring several lines. Otherwise the rest is moved to the front and recv fills the free space: a line may come in pieces. A line longer than the buffer is dropped, and one longer than cap is cut; a final line without newline is lost at the end of the stream, a choice to document. The test sends lines one byte at a time, including an empty line.
Exercise 16.8 ★★
Prove Proposition 16.10 by induction on . Show by an example that with a delimiter, and a message that contains the delimiter, decoding is not unique.
Solution
Solution of Exercise 16.8.
By induction on . For , is empty, and decoding yields nothing and uses all of it. Let and , where is 4 bytes holding followed by , and is the concatenation of the framings of . Decoding reads the first 4 bytes of , which are those of , so it reads ; it then takes the next bytes, which are , and starts again at the first byte of . By the induction hypothesis, decoding yields and uses all of . So decoding yields and uses all of it. The key point is that the decoder never has to guess where a message ends: the length says so before any byte of the message is read.
With the newline as delimiter, the single message made of a, a newline and b, and the two messages a and b, are both sent as the four bytes a, newline, b, newline: the receiver cannot tell them apart.
Exercise 16.9 ★★
Write a server with a thread per client, in which each line a client sends is answered with the number of lines received from all clients so far.
Solution
Solution of Exercise 16.9.
static void *client_thread(void *arg)
{
int c = (int)(intptr_t)arg;
struct linereader r;
lr_init(&r, c);
char line[256], reply[32];
while (lr_line(&r, line, sizeof line) >= 0) {
pthread_mutex_lock(&m);
long now = ++lines; /* read and change under the lock */
pthread_mutex_unlock(&m);
int n = snprintf(reply, sizeof reply, "%ld\n", now);
if (send_all(c, reply, n) != 0)
break;
}
close(c);
return NULL;
}
The count is shared by every thread, so its increment and the read of its new value are one critical section; reading lines again after unlocking could return another thread’s number. The reply is formatted and sent outside the lock, so that a slow client does not hold the others up. The line reader of Exercise 16.7 cuts the stream into lines. The test runs 4 clients of 50 lines each and checks that the server counted 200, and that no reply exceeds 200.
Exercise 16.10 ★★★
Write a chat server with poll: each line a client sends is sent to every other connected client.
Solution
Solution of Exercise 16.10.
void chat_serve(int lfd, int total) /* until `total` clients came and left */
{
struct client cl[MAXC];
struct pollfd p[MAXC + 1];
int n = 0, seen = 0;
while (seen < total || n > 0) {
p[0] = (struct pollfd){.fd = seen < total ? lfd : -1, .events = POLLIN};
for (int i = 0; i < n; i++)
p[i + 1] = (struct pollfd){.fd = cl[i].fd, .events = POLLIN};
poll(p, n + 1, -1);
for (int i = n - 1; i >= 0; i--) {
if (!(p[i + 1].revents & (POLLIN | POLLHUP)))
continue;
struct client *c = &cl[i];
ssize_t k = recv(c->fd, c->buf + c->len, sizeof c->buf - c->len, 0);
if (k <= 0) { /* gone: close and forget */
close(c->fd);
cl[i] = cl[--n];
continue;
}
c->len += k;
char *nl;
while ((nl = memchr(c->buf, '\n', c->len))) { /* every complete line */
size_t len = nl - c->buf + 1;
broadcast(cl, n, i, c->buf, len);
memmove(c->buf, c->buf + len, c->len - len);
c->len -= len;
}
if (c->len == sizeof c->buf)
c->len = 0; /* a line too long: dropped */
}
if ((p[0].revents & POLLIN) && n < MAXC) {
cl[n] = (struct client){.fd = accept(lfd, NULL, NULL)};
n++, seen++;
}
}
}
poll, one buffer per client code/bachelor-2/16-sockets/exercises/chat.cEach client has a buffer in which partial lines wait; every complete line is sent to every other client, and removed. A client that closes, or fails, is closed and forgotten, its slot taken by the last one (the loop runs downwards so that the moved entry has already been handled). The listening socket is in the set only while clients may still come. send_all may block if a client stops reading; a server for real use would keep an outgoing buffer per client and ask poll for POLLOUT. The test connects three clients, sends a line from one and checks that the two others receive it, then the same from another.
Exercise 16.11 ★★★
Model the time per connection of each design as a fixed cost plus the cost of a request, the same for all. From Output 16.7, estimate for a process and for a thread, taking for the event loop. How many requests per connection would make the process design reach 90 % of the event loop’s rate?
Solution
Solution of Exercise 16.11.
Eight clients keep the server busy, so the time per connection is the inverse of the rate. On the run printed, the event loop takes µs per connection, which we take as . The thread design takes µs, so µs for a thread; the process design µs, so µs for a process. With requests per connection, a design serves requests per unit of time, against for the event loop. The process design reaches 90 % of it when , that is requests per connection. The model ignores everything else, such as the eight client threads competing for the same cores; it says that the fixed cost of a design matters only for short connections.
Exercise 16.12 ★★★
Explain the output of this experiment, in which a server closes a connection first, ends, and then a new server binds the same port without and with SO_REUSEADDR.
$ gcc -std=c17 -O2 -Wall -Wextra -o reuse reuse.c net.c -lm && ./reuse
bind with SO_REUSEADDR = 0: Address already in use
bind with SO_REUSEADDR = 1: ok
Solution
Solution of Exercise 16.12.
The side that closes a TCP connection first keeps it, after the exchange of closing messages, in the state TIME_WAIT for a while, so that a late packet of the old connection cannot be taken for part of a new one with the same addresses and ports. Here the server closed first, so its end, bound to port 44 169, is in TIME_WAIT after the program has closed every descriptor. A new bind to that port then fails with EADDRINUSE, unless SO_REUSEADDR is set, which allows binding an address whose only users are such lingering connections (it still refuses while another socket is listening on it). This is why a server restarted at once fails without the option, and why every server of the chapter sets it.
16.7 Problem: The town directory service
Problem 16.1
Weekend problem — The town directory service
The problem follows the directory service of Output 16.6 from its protocol to its load test.
Part I — The protocol.
- Write the bytes of the framed request
who 1, as the server receives them. - What is the largest message a 4-byte length can describe? Why does
recv_msgtake a capacity? - A client sends
who 1andwho 2on one connection, back to back. Can the server’s firstrecvreturn parts of both? Why does framing make it harmless? - The answer to
who 1is 39 bytes long. Write its first four bytes. - The Python client writes
struct.pack("!I", n). What would"<I"send instead, and what would the C server then read as the length ofwho 1? - Why is the reply for an unknown request a message, rather than a closed connection?
Part II — The server.
- List the system calls of
tcp_listen, in order, and say what each one does. - What does
acceptreturn, and why is it a new descriptor rather than the listening one? - In
handle, what happens if a client connects and sends nothing, with each design? - Use Proposition 16.7 to show that
recv_msgreturns a whole message or . send_allpassesMSG_NOSIGNAL. What would happen to the server without it, when a client closes before its answer is sent (Chapter 14)?- Why does the demo server serve exactly four connections and stop?
Part III — Concurrency, three ways.
- In
serve_fork, why must the parent closec? What would happen to the clients otherwise? - In
serve_threads, why is the descriptor passed by value, cast to a pointer, and not as&c? - The threads share
directory_answer’s tables. Why is no lock needed? - In
serve_poll, what happens when a request arrives in two pieces? - Why does
serve_pollwalk its array from the end when it removes entries? - Which design survives a handler that crashes with a segmentation fault, and which do not?
Part IV — The load test.
- How many connections does each design receive, and from how many threads?
- Why does the load test run each server in a child process rather than a thread of its own?
- Why is the measured time taken on the clients’ side?
- Order the designs by Output 16.7 and give the ratio of the fastest to the slowest.
- Why might the order change if each connection carried a thousand requests?
- State the result: requests per second on loopback for the three server designs, on the laptop.
Solution
Solution of Problem 16.1.
1. 00 00 00 05 77 68 6f 20 31: the length 5, then w, h, o, a space, 1.
2. bytes, about 4 GiB. A malicious or broken client could announce that much; the capacity bounds what the server agrees to receive, and recv_msg returns for a longer message instead of overflowing its buffer.
3. Yes: the stream keeps no boundaries, and the first recv may return all 18 bytes. Framing makes it harmless, because the decoder takes exactly the announced length and leaves the rest for the next message (Proposition 16.10).
4. 39 = 0x27: 00 00 00 27.
5. "<I" is little-endian: 05 00 00 00. The server would read as the length, more than its capacity, and recv_msg would return : the server would close without an answer.
6. A closed connection says only that something went wrong; an error message says what, and lets the client tell a mistake in its request from a broken server or network.
7. socket creates a stream socket; setsockopt sets SO_REUSEADDR; bind gives it the address 127.0.0.1 and the port; listen makes it a listening socket with a queue of 128 pending connections.
8. A new descriptor for the one connection with that client. The listening socket goes on receiving other clients’ connections; each connection needs its own descriptor to send and receive on.
9. recv_msg waits for 4 bytes. With a process or a thread per connection, only that child or thread waits, the others go on. In the event loop, poll never reports the silent connection ready, so the loop goes on too; the connection simply stays in the set (until the client leaves).
10. recv_all(fd, len, 4) returns 4 with the length, or fewer at the end of the stream, and recv_msg returns unless it got 4. Then recv_all(fd, buf, n) returns with the message, or fewer, and again recv_msg returns unless it got . So it returns with a whole message, or .
11. A write to a connection the client has closed raises SIGPIPE, whose default action ends the process: the whole server would die because of one client. With MSG_NOSIGNAL, send fails with EPIPE and only that connection is closed.
12. It is told to: its third argument is the number of connections to serve, 4 here, one per request of the client. A server that never stops would leave the session waiting.
13. The parent’s copy keeps the connection open: the client would see end of stream only when both copies are closed, and each such connection would hold a descriptor in the parent until it ran out of them.
14. &c points to a variable that the next turn of the loop overwrites, perhaps before the thread has read it: two threads could serve the same descriptor. The value itself, carried in the pointer, belongs to the thread.
15. The tables are written once, before the server starts, and only read afterwards. Readers alone do not form a data race.
16. The first piece is appended to st[i].buf; unframe finds the message incomplete and the connection stays in the set. When the second piece arrives, poll reports it again, and the request is then complete.
17. Removing entry moves the last entry into slot . Walking downwards, that last entry has already been handled in this round; walking upwards, it would be skipped in this round (the copy carries its own revents, but the loop has passed slot ), and since poll reports a ready descriptor again, it would be served only after the next call. Walking downwards serves every ready entry at once.
18. The process per connection: a crash kills only that child. A thread’s crash kills the whole process, every thread with it; the event loop is one thread, so it dies too.
19. connections, from 8 client threads.
20. The server must be measured as a separate program, as it would run: in a child process, its fork copies only the small server, not the client threads, and a crash or a stuck thread of one side does not take the other with it.
21. The clients see the whole service time, from the first connection to the last answer, which is what a user experiences; the server cannot know when the clients are done.
22. Event loop, thread per connection, process per connection; on the run printed the event loop is about times as fast as the process design.
23. The fixed cost per connection would be paid once for a thousand requests, so the three designs would come close (Exercise 16.11); the threads and processes might even pull ahead, using several cores where the event loop uses one.
24. Requests per second on loopback for three server designs, on the laptop: about 3 700 with a process per connection, 7 300 with a thread per connection and 10 900 with an event loop, in the run printed (3662, 7331 and 10 917).