WebSocket, HTTP vs WebSocket, and Socket.IO – Class Note
1. What is WebSocket?
WebSocket is a communication protocol, just like HTTP, FTP, and SMTP. The main purpose of WebSocket is to allow real-time, continuous communication between a client (browser/app) and a server.
Unlike traditional request-based systems, WebSocket keeps a persistent connection open once it is established. This means data can flow at any time without repeatedly creating new requests.
Common use cases:
2. HTTP vs WebSocket
HTTP Communication
HTTP follows a request–response model.
This makes HTTP client-driven. The server cannot send data on its own.
Diagram (HTTP):
Client ---- request ----> Server
Client <--- response ---- Server
(connection closed)
Because of this limitation, HTTP is not ideal for real-time features. To simulate real-time behavior, techniques like polling or long polling are used, which are inefficient.
WebSocket Communication
WebSocket allows two-way (bi-directional) communication.
This makes WebSocket event-driven and real-time.
Diagram (WebSocket):
Client <==== open connection ==== > Server
Client ---- data ---->
Client <---- data ----
(both can send anytime)
So unlike HTTP, communication here is simultaneous and continuous.
3. What is Socket.IO?
Socket.IO is a library, not a protocol. It uses WebSocket internally (and falls back to other techniques if needed) to make real-time communication easier and more reliable.
Socket.IO provides:
4. Understanding io and socket (Circuit Analogy)
Think of the server as an electric circuit.
Diagram:
Client A (socket.id: 1)
|
|
Client B (socket.id: 2) --- [ io / Server Circuit ] --- Client C (socket.id: 3)
|
|
Client D (socket.id: 4)
Each socket has a unique identifier, accessible using:
socket.id
This ID helps the server identify which client it is communicating with.
5. Events in Socket.IO (How Communication Happens)
Socket.IO works on an event-based system.
emit
Used to send or trigger an event with data.
on
Used to listen for an event and receive its data.
6. Server-side Events
Send message to everyone
io.emit("event1", "hi")
This sends "hi" to all connected clients.
Listen to an event from a client
socket.on("btn", (n) => {
// n is data sent by client
})
Here, the server is listening for the btn event from a specific socket.
7. Client-side Events
Listen for server event
socket.on("event1", (m) => {
console.log(m)
})
The client listens for event1 and receives data m.
Send event to server
socket.emit("btn", 4)
This sends the value 4 to the server with the event name btn.
8. Broadcasting
Broadcasting means sending data to all clients except the sender.
Conceptually:
9. Rooms and Personal Messaging
Socket.IO allows grouping sockets into rooms.
Diagram (Rooms):
Room A: socket 1, socket 3
Room B: socket 2, socket 4
This helps in:
10. Summary Concept