CSE Roadmap

Core tier · about 5 hours · 7 parts

Part 2 of 7 · 3 min read

The service

Think of it this way. A restaurant has a front door where guests arrive and a table for each party. The door only lets guests in, and the waiter at the table does the serving. A network server has the same shape: one place that accepts new visitors, and some code that serves each one. The analogy stops where it comes to cost: a table is free, but each served client costs memory and a thread.

In plain words: The service is deliberately tiny. A client connects, sends a number as text, and the server replies with that number doubled. A client may send many requests on the same connection. To imitate a real service that waits on a database, the server sleeps 20 milliseconds before every reply. Everything runs on the same machine, through the loopback address 127.0.0.1.

Three terms are needed. A socket is the operating system's object for one end of a network conversation. A port is a number that tells the system which program on the machine should receive an incoming connection (here 9100). The loopback address is a built-in address that sends data back to the same machine, so no network card is involved.

The server uses these calls, from the Linux interface:

Call Job
socket create a socket
bind attach it to an address and a port
listen mark it as waiting for incoming connections
accept wait for one client, and return a new socket for that client
read and write exchange bytes with that client
close end the connection

The socket created first is the listening socket. Each accept returns a different socket, one per client. The listening socket never carries data.

The code that serves one client is shared by all designs:

static void serve(int fd) {
    char buf[64];
    ssize_t k;
    while ((k = read(fd, buf, sizeof buf - 1)) > 0) {
        buf[k] = 0;
        long n = atol(buf);
        usleep(20000);                       /* stands in for a database wait */
        char out[64];
        int m = snprintf(out, sizeof out, "%ld\n", n * 2);
        if (write(fd, out, m) < 0) break;
    }
    close(fd);
}

read returns 0 when the client closes its end, and the loop ends. The function is written once and reused, which is the point: the designs differ only in who calls serve, and on which thread.

Socket

A socket is an operating-system object that represents one end of a communication channel, identified to the program by a file descriptor, and used with read and write like a file.

Example: accept returns a new socket for each connecting client, and close on it ends that conversation.

Check yourself: 1. What does the listening socket do, and what does it not do? 2. Why does read returning 0 end the loop? 3. What is the loopback address for?