Websockets
A WebSocket is a persistent, two-way connection between a browser and a server over a single TCP link, letting both sides send messages to each other instantly — ideal for chat, live updates, and other real-time features.
Learn Python, JavaScript, Java and more with free interactive lessons, real projects and AI-powered help. Beginner-friendly.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
WebSocket examples require a server to connect to. For the best experience: Download Node.js to run a local WebSocket server, use your browser's Developer Console (Press F12) to test the WebSocket API, or try online WebSocket testing services.
Master real-time communication: persistent connections, messaging patterns, presence, rooms, and scalable architecture.
What You'll Learn
HTTP is request → response only. WebSockets allow persistent, two-way communication : the server can push events anytime, and the client can send events anytime — no need for repeated HTTP requests.
Chat systems • Live notifications • Real-time games • Stock tickers • Collaborative editing • Multiplayer interactions • Typing indicators • Presence systems • Live dashboards
The browser's WebSocket API is simple but powerful. Always use wss:// for secure connections.
WebSockets only send text or binary. Best practice is to use structured JSON messages with type fields to handle different event types.
WebSocket connections will always drop eventually (network issues, server restarts, etc.). Production apps must auto-recover with exponential backoff.
Every WebSocket system needs a heartbeat to detect dead connections. Clients ping periodically; if no pong returns, the connection is considered dead.
Presence tracking shows who's online. It requires careful handling because disconnects aren't always clean (network loss, device sleep, etc.).
Real apps need grouping: chat rooms, game lobbies, per-user channels. Rooms allow targeted messaging instead of broadcasting to everyone.
WebSockets do NOT guarantee message delivery. For critical messages, implement ACKs (acknowledgments) and retry logic.
WebSockets must be validated like any untrusted API. Always authenticate, validate messages, sanitize input, and rate limit.
A single server can't handle millions of users. Real systems use Redis/NATS/Kafka as a message bus to broadcast across multiple servers.
Practice quiz
How does a WebSocket differ from traditional HTTP?
- It only works on localhost
- It is request-response only and closes after each reply
- It provides a persistent, two-way connection where the server can push data anytime
- It cannot send text
Answer: It provides a persistent, two-way connection where the server can push data anytime. Unlike HTTP's request-then-response model, a WebSocket keeps a persistent, bidirectional connection open so both sides can send messages anytime.
Which URL scheme is used for a secure WebSocket connection?
- wss://
- https://
- ftp://
- ws-secure://
Answer: wss://. wss:// is the secure WebSocket scheme (the WebSocket equivalent of https://).
Which event fires when a WebSocket connection is successfully established?
- 'message'
- 'close'
- 'error'
- 'open'
Answer: 'open'. The 'open' event fires when the connection is established; 'message' fires for incoming data.
Where do you read the data of an incoming WebSocket message?
- event.body
- event.data
- event.payload
- event.result
Answer: event.data. In the 'message' event handler, the received data is on event.data.
In the lesson, what does socket.readyState value 1 (OPEN) mean?
- The connection is open and ready to send
- The connection is closing
- The connection is connecting
- The connection is closed
Answer: The connection is open and ready to send. readyState 1 is OPEN (0=CONNECTING, 1=OPEN, 2=CLOSING, 3=CLOSED).
Why does the reconnection example use exponential backoff?
- To send messages faster
- To encrypt the data
- To space out reconnect attempts with increasing delays instead of hammering the server
- To avoid using JSON
Answer: To space out reconnect attempts with increasing delays instead of hammering the server. Exponential backoff increases the delay between reconnect attempts, avoiding overwhelming a struggling server.
What is the purpose of a heartbeat (ping/pong) system?
- To compress messages
- To detect dead connections when no pong returns within a timeout
- To authenticate users
- To create rooms
Answer: To detect dead connections when no pong returns within a timeout. Clients ping periodically; if no pong arrives within the timeout, the connection is treated as dead.
Do WebSockets guarantee message delivery on their own?
- Yes, always
- Only over wss://
- Only for JSON messages
- No — for critical messages you implement ACKs and retries
Answer: No — for critical messages you implement ACKs and retries. WebSockets do NOT guarantee delivery, so reliable messaging adds acknowledgments (ACKs) and retry logic.
What is the role of rooms/channels in the lesson?
- To encrypt messages
- To allow targeted messaging to a group instead of broadcasting to everyone
- To reconnect faster
- To store messages on disk
Answer: To allow targeted messaging to a group instead of broadcasting to everyone. Rooms group users so messages can be sent to a targeted set instead of every connected client.
How do you scale WebSockets across multiple servers in the lesson?
- Using a single giant server
- By disabling heartbeats
- Using a Pub/Sub message bus (like Redis) to broadcast across servers
- By switching to HTTP polling
Answer: Using a Pub/Sub message bus (like Redis) to broadcast across servers. A Pub/Sub pattern (Redis/NATS/Kafka) lets a message published on one server reach clients connected to all servers.