COE 558Lecture 01Part 05
Sockets and web app architecture
The socket API between your program and the transport layer, TCP versus UDP sockets, and the frontend and backend of a web application.
- Concepts
- 4
- Slides
- 40-45
- Reading
- 24 min
Why this part matters
Every service you will place on the edge-to-cloud continuum, whether a camera pipeline, an IoT gateway or a cloud API, ends up as processes talking through sockets. The socket type decides what happens to a lost or late packet. The split between frontend and backend decides which parts can move to the edge and which must stay near the database.
Exams ask for the socket call sequence and for a justified choice between TCP and UDP. Your research project needs the same reasoning to explain where latency comes from. This part builds both, climbing from the point where a program first touches the network up to a complete web application.
By the end you can
- Explain a socket as a file descriptor, addressed by IP and port, that the socket API creates
- Order the socket calls a TCP server and client make, and say what accept returns
- Choose TCP or UDP for a workload by what a lost or late unit of data costs
- Split a web application into browser client, server and database, and trace a saved form
- Read a backend route as method plus path plus handler and trace one HTTP request
Think about what your browser does when you open the KFUPM portal. It cannot put signals on the Wi-Fi radio or build TCP segments by itself. Instead it makes a few requests to the operating system: open a connection to this address and port, send these bytes, give me whatever comes back. The operating system does everything below that. Understanding exactly what that request looks like is the foundation for everything else in this part.
An API is a menu, and the socket API is the networking menu
The set of operations one piece of software offers to another is an Application Programming Interface, or API. Earlier in this lecture you saw that a relationship between components is a protocol plus an Interface. Here the interface sits between the Application layer (your program) and the Transport layer (TCP and UDP inside the operating system). For networking, that interface is the Socket API.
Kurose and Ross describe the socket as the door between the application process and TCP. As a developer you control everything on the application side of that door, and you have very little control over the transport side. The rest of this concept opens the door and looks at what is actually there.
What a program actually holds: a file descriptor
Make it concrete. In C, calling socket() returns a small integer, for example 3. From then on the program writes write(3, ...) exactly as it would for an open file. POSIX states that when the descriptor refers to a socket, write() is equivalent to send() with no flags, and the Linux manual says the only difference between recv() and read() is the flags argument.
So to a program, a Socket is an operating system object that it reads and writes like a file. The kernel takes the bytes you write and turns them into TCP segments or UDP datagrams, which is why the application never needs to know how either protocol works. Be careful with the words: the socket API is the interface, and a socket is the endpoint that the API creates and names.
Naming the endpoint: the socket address
A file on disk has a path; a socket has an address: an IP address plus a Port number, for example 10.0.0.5:443. The IP address finds the host and the port finds the process on that host, the same two-level addressing you met with the TCP/IP stack. RFC 9293 identifies a TCP connection by a pair of sockets, one at each end, so a connection is really four numbers: client IP and port, server IP and port.
One more ingredient completes the name. The protocol is fixed when the socket is created, so TCP port 53 and UDP port 53 are different endpoints even on the same host. DNS, as RFC 1035 specifies, listens on both.
The lifecycle of a connection
A Server and a Client play different roles, so they use different calls. The server must be findable before anyone arrives: it creates a socket, binds it to a well-known address, marks it as listening, then accepts connections one by one. The client already knows where to go, so it only creates a socket and connects. Once connected, both sides send and receive, then close.
Socket lifecycle, in call order
- socket()
- Both sides. Creates an endpoint and returns a file descriptor such as 3. It has no address yet.
- bind()
- Server. Attaches a local IP address and port, for example 0.0.0.0:443. The Linux manual calls this assigning a name to a socket, so clients know where to knock.
- listen()
- Server. Marks the socket as passive, ready to accept connections. The backlog argument caps the queue of pending connections. Connection-oriented sockets only (SOCK_STREAM or SOCK_SEQPACKET).
- connect()
- Client. For TCP it starts the connection, which runs the three-way handshake. For UDP it only records a default destination.
- accept()
- Server. Takes the first pending connection and returns a new connected socket with a new descriptor, for example 4. The listening socket is unaffected and keeps waiting.
- send() / recv()
- Both sides. Move bytes. On a socket, write() is send() with no flags, and read() is recv() with no flags.
- close()
- Both sides. Releases the descriptor and ends that side of the connection.
Worked example
One HTTPS request through the socket calls
Server prepares
The server calls socket() and gets descriptor 3, calls bind() to 0.0.0.0:443, then listen().Client connects
The browser calls socket() and connect() to the server address. The TCP three-way handshake runs.Server accepts
accept() returns descriptor 4, a socket dedicated to this client. Descriptor 3 keeps listening.TLS handshake
Both sides exchange TLS handshake messages with send() and recv() on the connected sockets. From here on the bytes on the wire are encrypted.Request
The client calls send() with the encrypted request bytes. The server calls recv() on descriptor 4.Response
The server calls send() on descriptor 4; the client calls recv().Finish
Both sides call close() on their connected sockets.Result
The server held two sockets for this exchange: descriptor 3 listening and descriptor 4 connected.
Recall
What does a program actually hold when it has a socket, and which ordinary calls can it use on it?
Recall
List the server-side calls in order. What does accept return, and what happens to the listening socket?
Quick check
An HTTPS server process has 1000 clients connected on port 443. Counting the listening socket, how many TCP sockets does it hold?
Once you know a program holds a socket, the next decision is which kind. Take two jobs. First, downloading a 2 GB dataset for your project: one missing byte corrupts the file, so every byte must arrive, in order. Second, a live video call: a voice frame that arrives 1 s late is useless, so waiting for it to be resent makes the call worse, not better. These two jobs need different sockets, and the difference is fixed the moment socket() is called.
Two services behind the same API
A TCP socket is a stream socket. RFC 9293 describes TCP as a reliable, in-order, byte-stream service. It sets up a connection with a three-way handshake, numbers every byte, checks it with a checksum and retransmits what is lost. That reliability costs setup time and state on both hosts, which is exactly the connection that listen(), connect() and accept() manage.
A UDP socket is a datagram socket. RFC 768 says UDP offers a minimum of protocol mechanism: delivery and duplicate protection are not guaranteed, and the header is just four 16-bit fields (source Port number, destination port, length, checksum), 8 bytes in total. There is no listen or accept: each datagram stands alone. POSIX names the two kinds SOCK_STREAM and SOCK_DGRAM.
| Property | TCP socket | UDP socket |
|---|---|---|
| POSIX type | SOCK_STREAM | SOCK_DGRAM |
| Connection setup | Three-way handshake before any data | None, each datagram stands alone |
| Delivery | Lost segments detected and retransmitted | No delivery or duplicate guarantee |
| Ordering | Bytes reach the application in order | Datagrams may arrive out of order |
| Message boundaries | A continuous byte stream, no boundaries | Each datagram is one whole message |
| Header overhead | 20 bytes minimum, plus connection state | 8 bytes, four 16-bit fields |
| Typical uses | Web pages, file transfer, email | DNS queries, voice and video calls |
Choosing a socket for a workload
The right question is not which is faster. Ask what happens to your application when one unit of data is lost or late. If it must be recovered, use TCP. If late data is worthless, or the exchange is tiny and easy to retry, UDP avoids overhead that buys you nothing. For interactive media this is really about Latency: a retransmitted frame arrives after its moment has passed.
| Workload | Socket | Why |
|---|---|---|
| Web page over HTTP/1.1 or HTTP/2 | TCP | Every byte of HTML and script must arrive intact. Default ports 80 and 443. |
| File transfer (FTP) and email | TCP | One missing byte corrupts the file or message. |
| DNS query | UDP | A small single exchange that can simply be retried. Port 53, with TCP 53 for zone transfers and long answers. |
| Video call (WebRTC) | UDP | A late frame is useless, so retransmission only hurts. TCP through a relay is a fallback. |
| Web page over HTTP/3 | UDP (carrying QUIC) | QUIC adds reliable streams and encryption on top of UDP. |
The last row of that table shows that the choice is not always binary. RFC 9114 defines HTTP/3 as the same HTTP semantics over a new transport, QUIC, and RFC 9000 says QUIC packets are carried in UDP datagrams. QUIC rebuilds reliable streams, flow control and encryption in user space on top of UDP. So choosing UDP does not always mean giving up reliability. It means a protocol or library above UDP decides how much reliability to add, and when.
Quick check
A video call plays 50 voice frames per second and playback never pauses to wait. Which socket fits best, and why?
Quick check
HTTP/3 keeps the same HTTP semantics but changes the transport underneath. What does it run on?
Recall
Why do DNS queries use UDP while file transfers use TCP, and where does HTTP/3 fit?
Now bring sockets to the web. You type https://uni.majid.app and press Enter. The browser resolves the name, asks the operating system to open a TCP connection to port 443 (or QUIC over UDP for HTTP/3), sends the HTTP request, reads the response, and may reuse the same connection for the next requests. The page code only calls fetch("/api/...") and never sees a Socket.
The browser owns the client socket
A web application is a Network application in which the browser is the Client program and owns the client socket: when to open it, reuse it and close it. MDN puts it simply: browsers communicate with web servers using HTTP, by sending a request to the server. Every socket call from the lifecycle above is still happening, just inside the browser and inside the server runtime.
This changes the level at which you work. Frontend code for the World Wide Web is written in terms of HTTP requests, and backend code is written in terms of routes that answer them. The socket becomes infrastructure you rely on rather than an object you manage.
Recall
In a web application, who manages the client socket, and at what level does the frontend code work?
Three components: client, server, database
So what is on the other end of that connection? Picture a course portal. You submit a homework answer. The browser sends a request over the Internet. The server checks it and writes a row to the database. When you reopen the page later, the server reads that row and sends it back in a response.
The pieces have names. The Frontend is one Component: the client. The Backend is two components: the Server and the database. The client talks only to the server, never directly to the database. MDN describes the same flow: on a request, the server fetches data from the database and builds the response. This is the Request-response loop you met with network applications, and the client always starts it.
Browser: HTML, CSS, JavaScript
Checks requests, runs the logic, builds responses
Stores data that must survive between requests
Look at the server to database link closely, because it reuses everything from the first concept. It is itself a client-server connection over sockets, with the web server acting as the database client. Writes flow from server to database and reads flow back. A web application is therefore a chain of socket conversations, each with its own client and server role.
Why server and database often live apart
- They scale separately: many identical server instances can share one carefully managed database.
- Their resource needs differ: the server wants CPU, the database wants disk and memory.
- The database can be kept off the public Internet, reachable only from the servers.
This is the first placement decision on the edge-to-cloud continuum. Later parts ask where the server and the database should each live, and every placement has a cost: each read or write between separate machines adds its own network Round-trip time (RTT), which later feeds into Response time (RT).
Quick check
A user saves a form on a web app and the data must persist. Which path does it take?
Recall
Name the two backend components of a web application, and give one reason they often run on different machines.
The architecture becomes real when you read the code on each side. Consider a calculator running in the browser and the backend that serves it. Walk one request through: the user opens the About view, and the frontend sends GET /calculadora/about.
From request to handler to response
On the Backend, the framework compares the request method and path against its routes. It finds the route with method GET and path /calculadora/about and calls its handler, handler(request, h). The handler builds an object with a message field and returns it. In hapi, a returned plain object becomes the response payload, serialized as JSON. The browser receives that JSON in the HTTP response body and the Frontend renders it.
The general rule: a route is a method plus a path plus a handler. The set of routes a backend exposes is its Web API, the Interface the frontend programs against, while HTTP is the Protocol carried between them. Protocol plus interface again, one level higher than the socket API. Underneath, the Node.js runtime owns a listening socket and one connection socket per Client, exactly the welcoming door picture from the first concept.
Worked example
Tracing GET /calculadora/about
Request
The browser sends GET /calculadora/about over its connection to the server.Route match
The framework matches method GET and path /calculadora/about to the registered route.Handler
handler(request, h) runs and returns an object with a message field.Serialize
The framework turns the object into a JSON response body.Response
The response travels back over the same connection, closing the Request-response loop.Result
What the handler returns is exactly what the browser receives, as JSON.
Same language, different machines
Notice the languages. The frontend uses HTML for structure, CSS for presentation and JavaScript for behaviour, all inside the browser. The backend also runs JavaScript, but in the Node.js runtime on the Server. Same language, different processes on different machines, joined only by HTTP over a socket.
| Side | Runs where | Written in | Role |
|---|---|---|---|
| Frontend | Inside the browser on the user machine | HTML, CSS, JavaScript | Draws the calculator and sends HTTP requests |
| Backend | In the Node.js runtime on a server | JavaScript (hapi on Node.js) | Matches routes and returns data in responses |
Recall
What three things make up a backend route, and what does the client receive when the route is hit?
Recap
If you remember nothing else
- An API is how software asks other software for a service. The socket API is the door from the application layer to the transport layer.
- A socket is a file descriptor. Programs read and write it like a file, and it is addressed by IP address plus port.
- Servers call socket, bind, listen and accept. Clients call socket and connect. accept returns a new socket per client.
- TCP sockets give a reliable, ordered byte stream with connection overhead. UDP sockets send independent datagrams with minimal overhead.
- Choose by what a lost or late unit costs: files and web pages use TCP, DNS queries and video calls use UDP, and HTTP/3 runs on QUIC over UDP.
- In a web app the browser manages the client socket. The backend is a server plus a database that may run on different machines.
- A backend route is method plus path plus handler, and what the handler returns becomes the HTTP response.
Sources
- Computer Networking: A Top-Down Approach, section 2.7 Socket Programming with TCPBookKurose and Ross, UMass AmherstSocket as the door to TCP, welcoming and connection sockets(opens in a new tab)
- Computer Networking: A Top-Down Approach, 9th editionBookKurose and Ross(opens in a new tab)
- socket(): POSIX.1-2024DocsThe Open Group and IEEEReturns a socket file descriptor; SOCK_STREAM and SOCK_DGRAM(opens in a new tab)
- write(): POSIX.1-2024DocsThe Open Group and IEEEOn a socket, write equals send with no flags(opens in a new tab)
- bind(2)DocsLinux man-pages project(opens in a new tab)
- listen(2)DocsLinux man-pages project(opens in a new tab)
- accept(2)DocsLinux man-pages project(opens in a new tab)
- connect(2)DocsLinux man-pages project(opens in a new tab)
- recv(2)DocsLinux man-pages project(opens in a new tab)
- RFC 9293: Transmission Control Protocol (TCP)RFCIETF(opens in a new tab)
- RFC 768: User Datagram ProtocolRFCIETF(opens in a new tab)
- RFC 9000: QUIC, A UDP-Based Multiplexed and Secure TransportRFCIETF(opens in a new tab)
- RFC 9114: HTTP/3RFCIETF(opens in a new tab)
- RFC 9110: HTTP SemanticsRFCIETFDefault ports 80 and 443; HTTP/3 over QUIC(opens in a new tab)
- RFC 1035: Domain Names, Implementation and SpecificationRFCIETFDNS on UDP and TCP port 53(opens in a new tab)
- RFC 8835: Transports for WebRTCRFCIETF(opens in a new tab)
- RFC 959: File Transfer ProtocolRFCIETF(opens in a new tab)
- Fetch Living StandardDocsWHATWGThe browser obtains and reuses connections for fetch(opens in a new tab)
- Net module (node:net)DocsNode.js(opens in a new tab)
- hapi API reference: server.route and lifecycle methodsDocshapi.js project(opens in a new tab)
- Client-Server overviewDocsMDN Web Docs(opens in a new tab)