Network Protocols

What Are Network Protocols❔

Network protocols are rules or standards that allows computers to communicate with each other over the network. They define how data is formatted, transmitted, and received.

Think of them as the languages or grammar rules for devices to understand each other during communication.

What is the OSI (Open Systems Interconnection) Model

The OSI model is a conceptual framework that describes how data moves from one computer to another over a network in 7 layers.

Each layer has  a specific role and communicates only with its adjacent layers.

OSI Model - 7 Layers (Top to Bottom)

LayerNameFunctionExamples
7ApplicationInterfaces with user appsHTTP, HTTPS, FTP, DNS
6PresentationData formatting, encryption, compressionSSL/TLS, JPEG, MP3
5SessionEstablish/manage sessionsNetBIOS, PPTP, RPC
4TransportReliable/unreliable data transferTCP, UDP
3NetworkRouting and addressingIP, ICMP, ARP
2Data LinkFrame transfer, MAC addressingEthernet, PPP, MAC
1PhysicalActual transmission of bitsCables, NICs, Wi-Fi, Fiber

1 Physical Layer

  • Deals with hardware transmission of raw bits.
  • Concerned with cables, voltages, pins, etc.
  • Examples: Ethernet cables, fiber optics, switches.

2 Data Link Layer

  • Ensures error-free data transfer between two directly connected devices.
  • Uses MAC addresses for device identification on a LAN.
  • Examples: Ethernet, Wi-Fi (802.11), switches, ARP.

3 Network Layer

  • Handles routing of data across multiple networks.
  • Assigns IP addresses and manages packet delivery.
  • Examples: IP (IPv4/IPv6), ICMP (used in ping), routers.

4 Transport Layer

  • Provides end-to-end connection, error checking, and flow control.
  • Can be reliable (TCP), or fast (UDP).
  • Examples: TCP (used in HTTP), UDP (used in video streaming).

5 Session Layer

  • Manages sessions or connection between devices.
  • Keeps track of which systems are talking and for how long.
  • Examples: NetBIOS, RPC, PPTP.

6 Presentation Layer

  • Formats and encrypts data to be readable by the application.
  • Handles data serialization, encryption, and compression.
  • Examples: SSL/TLS, JPEG, ASCII, MP4.

7 Application Layer

  • Closet to the end user, the top most layer.
  • It directly interacts with end-user. It handles protocols that manage communication between software applications.
  • Provides network services like browsing, email and file transfers.
  • Examples: HTTP, FTP, SMTP, DNS.

Real-Life Analogy: Sending a Letter

OSI LayerReal-Life Analogy
ApplicationYou write a message
PresentationYou write in English, or encode it
SessionYou start and end the conversation
TransportYou number pages and ensure order
NetworkThe post office routes it via cities
Data LinkThe local delivery truck takes it to you
PhysicalThe road and vehicle physically carry it

🔄 How It Works Together (Simplified)

When you visit a website:

  1. HTTP (Application Layer) forms your request.
  2. It's encrypted (Presentation).
  3. A session is opened (Session).
  4. TCP breaks it into segments (Transport).
  5. IP routes it (Network).
  6. It's framed and sent via MAC address (Data Link).
  7. Finally, 0s and 1s travel through a cable (Physical).

Application Layer Models

1️⃣ Client-Server Model

  • One machine (client) requests resources.
  • Another machine (server) responds with resources.
  • Examples:
    • Web browsing (Browser <-> Web Server)
    • Email (Email Client <-> Mail Server)
  • Real-Life Analogy:
    • You (client) go to a restaurant and ask a waiter (server) for food.

Protocols at this Layer:

1 HTTP (Hypertext Transfer Protocol)

  1. Port: 80 (HTTP), 443 (HTTPS)
  2. Stateless: Each HTTP request is independent.
  3. Use Case: Web page requests, REST APIs.

2 HTTPS (HTTP Secure)

  1. Runs HTTP over SSL/TLS for encryption
  2. Used in secure websites, online banking, and e-commerce.

How it works:

  1. Client (browser) sends HTTP requests to server.
  2. Server responds with HTML/CSS/JS.
  3. Connection closes (stateless).
  4. Cookies/sessions used for state tracking.

HTTP Methods:

MethodPurpose
GETRetrieve data
POSTSubmit data
PUTReplace a resource
PATCHUpdate part of a resource
DELETERemove a resource
OPTIONSDiscover supported methods
HEADLike GET, but no body

Status Code:

CategoryCodeMeaning
📗 Success200OK
 201Created
 204No Content
⚠️ Client Errors400Bad Request
 401Unauthorized
 403Forbidden
 404Not Found
🔴 Server Errors500Internal Server Error
 502Bad Gateway
 503Service Unavailable

Tools to Work with HTTP

  • Postman: Test HTTP APIs
  • curl/wget: CLI tools
  • Wireshark: Inspect HTTP packets
  • Browser DevTools: Network Tab

What is Polling?

Polling is a technique where the client repeatedly sends HTTP requests to the server at regular intervals to check if new data is available.

Polling is a technique where the client repeatedly asks the server: Do you have new data?

This is done by sending HTTP requests at regular time intervals, even if there's nothing new to report.

Polling is a communication technique that uses HTTP to simulate real-time behavior in web applications.

Imagine you are waiting for a package:

  • Instead of the delivery guy knocking at your door.
  • You kept opening the door at every 10 minutes looking for the delivery guy.
  • This is the polling.
ComponentRole
ClientSends repeated requests
ServerResponds with data (or nothing)
ProtocolUsually HTTP
IntervalFixed time (e.g. every 5 sec)
What Actually Happens in Normal HTTP

In a standard web application:

  1. You open a web page.
  2. The browser sends an HTTP request to the server.
  3. The server sends back the HTML/CSS/JS.
  4. The connection closes.
  5. That's it – until you do something (click, refresh, etc.).

There's no automatic “polling” happening behind the scenes.

When Does the Browser Poll?

When the website includes code like this:

setInterval(() => {
  fetch('/notifications') // or use XMLHttpRequest
    .then(res => res.json())
    .then(data => console.log(data));
}, 5000); // Every 5 seconds

Now the browser polls the server every 5 seconds – but only because the app told it to.

Types of Polling:

  1. Short Polling
    1. Fixed time interval (e.g., every 3 seconds)
    2. Common but inefficient
    3. Easy to implement
    4. Can cause:
      1. Higher server load
      2. Wastes resources if no new data
      3. Delays in receiving messages
  2. Long Polling:
    1. Client sends request, and server holds the connection open until new data is available (or timeout occurs).
    2. More efficient than short polling
    3. Used in early real-time web apps

When is Polling Used?

  • Early chat apps.
  • Email notifications (e.g., “You have got mail”
  • Stock dashboards (without real-time connection)
  • Backup for WebSocket/SSE in unreliable networks

4 WebSocket

This protocol creates a persistent, two-way (full-duplex) communication channel between the client (browser) and the server over a single TCP connection.

Unlike HTTP, where client must always start the communication, WebSocket allows both client and server to talk to each other anytime, like a phone call instead of sending letters.

Why use WebSocket?
FeatureHTTP (REST)WebSocket
ConnectionOne request = one responsePersistent connection
DirectionClient → ServerBi-directional (full-duplex)
Real-time❌ No✅ Yes
Use CasesStatic websites, APIsChat apps, live games, stock tickers

Implementation of WebSocket

Client-side (Browser)

Modern browsers (Chrome, Firefox, Edge, etc.) have native support for WebSocket via the WebSocket object:

// Example (vanilla JS in browser):

const socket = new WebSocket("wss://example.com/socket");

socket.onopen = () => {
  console.log("Connected!");
  socket.send("Hello Server!");
};

socket.onmessage = (event) => {
  console.log("Message from server:", event.data);
};

👉 No libraries required here – it's built into the browser.

Server-side (Node.js):

Here's where we commonly use a library, unless we want to manually handle low-level socket upgrades and frames.

LanguageLibraryNotes
Node.jswsMost popular, lightweight
Node.jssocket.ioAdds extra features (rooms, fallback, etc.)
PythonwebsocketsAsync-friendly WebSocket server
PythonFastAPI + WebSocketsClean, modern async support
JavaSpring WebSocketEnterprise-style support
Gogorilla/websocketWell-known Go library
// Example (Node.js with ws library)
npm install ws
const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
  console.log('New client connected!');
  ws.send('Hello from server!');

  ws.on('message', (message) => {
    console.log('Received:', message);
  });
});

💡 When you might need a library

  • If you are building the server.
  • If you want advanced features: reconnection, fallback to HTTP polling, rooms, broadcasting, etc.

⚠️ Caution: Don't confuse WebSocket with Socket.io:

  • WebSocket is the standard protocol
  • Socket.io is a library that uses WebSocket under the hood, but adds extra layers and may fall back to HTTP polling if needed.

5 SSE

SSE is a standard allowing the server to push updates to the client over a single long-lived HTTP connection.

Unlike WebSockets (which are bidirectional), SSE is one-way – server to client only.

FeatureSSE
Communication TypeOne-way (server → client)
TransportHTTP (specifically text/event-stream)
Browser SupportGood (not IE)
Reconnect SupportYes (built-in automatic reconnection)
Use Case FitNotifications, news feeds, live scores
ComplexityVery simple to use

🛠️ How SSE Works

  1. Client makes an HTTP request to the server.
  2. Server holds the connection open and sends updates as they become available.
  3. Each message is sent in the format of even:, data: lines.
  4. The client automatically reconnects if the connection drops.

2️⃣ Peer-to-Peer (P2P) Model

  • All nodes are equal – each can act as a client or server.
  • Resources are shared between peers, no central server.
  • Examples:
    • BitTorrent
    • Skype (older versions)
    • Blockchain networks
  • Analogy:
    • Everyone brings and shares food at a potluck party.