Lesson 94 – Introduction to JavaScript WebSockets
WebSockets provide a way to open a persistent, bi-directional communication channel between the browser and a server. Unlike HTTP requests (which are one-time and short-lived), WebSockets stay open and allow real-time data to be pushed both ways — ideal for live chats, gaming, notifications, and real-time updates.
What You’ll Learn
- What WebSockets are and how they work
- How to create a WebSocket connection in JavaScript
- Sending and receiving messages
- Common WebSocket events (
open
,message
,error
,close
)
What is a WebSocket?
A WebSocket is a communication protocol that allows:
- Real-time, full-duplex communication
- A single TCP connection to stay open
- Less overhead compared to polling or HTTP long-polling
WebSockets use the ws://
or wss://
protocol (secure WebSocket).
Basic WebSocket Example
// Create a WebSocket connection to the server
const socket = new WebSocket("wss://echo.websocket.org");
// Event: Connection opened
socket.addEventListener("open", function () {
console.log("Connection opened!");
socket.send("Hello server!");
});
// Event: Message received from server
socket.addEventListener("message", function (event) {
console.log("Message from server:", event.data);
});
// Event: Connection closed
socket.addEventListener("close", function () {
console.log("Connection closed.");
});
// Event: Error occurred
socket.addEventListener("error", function (error) {
console.error("WebSocket Error:", error);
});
- In the above code:
- We open a secure WebSocket connection to
wss://echo.websocket.org
(which echoes messages back). - We handle different WebSocket events like
open
,message
,close
, anderror
.
Real-world Use Cases of WebSockets
- Live chat applications (e.g. WhatsApp Web)
- Online multiplayer games
- Real-time stock price updates
- Live sports scoreboards
- Collaborative editing (Google Docs-style)
Notes on Security
- Use
wss://
for secure encrypted connections (just likehttps://
). - Implement authentication and message validation on the server side.
Summary
Feature | Description |
---|---|
Protocol | ws:// or wss:// |
Use Case | Real-time communication |
Keeps Connection Open | Yes |
Bi-directional | Yes |
Efficient? | More efficient than polling |
Try Your Hand!
Use the browser console to try the WebSocket connection. Here's a sample test site:
wss://ws.ifelse.io
You can connect using:
const ws = new WebSocket("wss://ws.ifelse.io");
ws.onopen = () => ws.send("Testing WebSocket!");
ws.onmessage = (e) => console.log("Received:", e.data);