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)
Layer | Name | Function | Examples |
---|---|---|---|
7 | Application | Interfaces with user apps | HTTP, HTTPS, FTP, DNS |
6 | Presentation | Data formatting, encryption, compression | SSL/TLS, JPEG, MP3 |
5 | Session | Establish/manage sessions | NetBIOS, PPTP, RPC |
4 | Transport | Reliable/unreliable data transfer | TCP, UDP |
3 | Network | Routing and addressing | IP, ICMP, ARP |
2 | Data Link | Frame transfer, MAC addressing | Ethernet, PPP, MAC |
1 | Physical | Actual transmission of bits | Cables, 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 Layer | Real-Life Analogy |
---|---|
Application | You write a message |
Presentation | You write in English, or encode it |
Session | You start and end the conversation |
Transport | You number pages and ensure order |
Network | The post office routes it via cities |
Data Link | The local delivery truck takes it to you |
Physical | The road and vehicle physically carry it |
🔄 How It Works Together (Simplified)
When you visit a website:
- HTTP (Application Layer) forms your request.
- It's encrypted (Presentation).
- A session is opened (Session).
- TCP breaks it into segments (Transport).
- IP routes it (Network).
- It's framed and sent via MAC address (Data Link).
- 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)
- Port: 80 (HTTP), 443 (HTTPS)
- Stateless: Each HTTP request is independent.
- Use Case: Web page requests, REST APIs.
2 HTTPS (HTTP Secure)
- Runs HTTP over SSL/TLS for encryption
- Used in secure websites, online banking, and e-commerce.
How it works:
- Client (browser) sends HTTP requests to server.
- Server responds with HTML/CSS/JS.
- Connection closes (stateless).
- Cookies/sessions used for state tracking.
HTTP Methods:
Method | Purpose |
---|---|
GET | Retrieve data |
POST | Submit data |
PUT | Replace a resource |
PATCH | Update part of a resource |
DELETE | Remove a resource |
OPTIONS | Discover supported methods |
HEAD | Like GET, but no body |
Status Code:
Category | Code | Meaning |
---|---|---|
📗 Success | 200 | OK |
201 | Created | |
204 | No Content | |
⚠️ Client Errors | 400 | Bad Request |
401 | Unauthorized | |
403 | Forbidden | |
404 | Not Found | |
🔴 Server Errors | 500 | Internal Server Error |
502 | Bad Gateway | |
503 | Service 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.
Component | Role |
---|---|
Client | Sends repeated requests |
Server | Responds with data (or nothing) |
Protocol | Usually HTTP |
Interval | Fixed time (e.g. every 5 sec) |
What Actually Happens in Normal HTTP
In a standard web application:
- You open a web page.
- The browser sends an HTTP request to the server.
- The server sends back the HTML/CSS/JS.
- The connection closes.
- 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:
- Short Polling
- Fixed time interval (e.g., every 3 seconds)
- Common but inefficient
- Easy to implement
- Can cause:
- Higher server load
- Wastes resources if no new data
- Delays in receiving messages
- Long Polling:
- Client sends request, and server holds the connection open until new data is available (or timeout occurs).
- More efficient than short polling
- 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?
Feature | HTTP (REST) | WebSocket |
---|---|---|
Connection | One request = one response | Persistent connection |
Direction | Client → Server | Bi-directional (full-duplex) |
Real-time | ❌ No | ✅ Yes |
Use Cases | Static websites, APIs | Chat 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.
Language | Library | Notes |
---|---|---|
Node.js | ws | Most popular, lightweight |
Node.js | socket.io | Adds extra features (rooms, fallback, etc.) |
Python | websockets | Async-friendly WebSocket server |
Python | FastAPI + WebSockets | Clean, modern async support |
Java | Spring WebSocket | Enterprise-style support |
Go | gorilla/websocket | Well-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 protocolSocket.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.
Feature | SSE |
---|---|
Communication Type | One-way (server → client) |
Transport | HTTP (specifically text/event-stream ) |
Browser Support | Good (not IE) |
Reconnect Support | Yes (built-in automatic reconnection) |
Use Case Fit | Notifications, news feeds, live scores |
Complexity | Very simple to use |
🛠️ How SSE Works
- Client makes an HTTP request to the server.
- Server holds the connection open and sends updates as they become available.
- Each message is sent in the format of
even:
,data:
lines. - 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.