HTML WebSocket API
The WebSocket API is a modern way to create a two-way (full-duplex) communication channel between a browser (client) and a server.
Unlike HTTP (which is request–response), WebSockets allow the server and client to send and receive data anytime without reopening a new connection.
👉 Use case: Live chat apps, stock tickers, multiplayer games, real-time notifications.
How WebSockets Work
- A WebSocket starts with an HTTP handshake (using
ws://
or securewss://
). - Once the handshake is successful, the connection upgrades from HTTP to WebSocket.
- Both client and server can now exchange data instantly.
Key point:
- HTTP = one-way (client requests, server responds).
- WebSocket = two-way (messages flow both directions).
Creating a WebSocket Connection
The WebSocket
constructor is used to open a connection.
Example:
// Create WebSocket connection
let socket = new WebSocket("ws://example.com/socket");
// Event when connection opens
socket.onopen = function() {
console.log("Connected to WebSocket server!");
};
If using HTTPS websites, always use wss://
(secure WebSocket).
Sending and Receiving Data
Once the connection is open, you can:
- Send messages with
.send()
. - Receive messages with
.onmessage
.
Example:
// Sending data to server
socket.send("Hello Server!");
// Receiving data from server
socket.onmessage = function(event) {
console.log("Message from server:", event.data);
};
You can send strings, JSON, or binary data (like images, files).
Handling WebSocket Events
The WebSocket API provides built-in events:
onopen
→ Fired when the connection is established.onmessage
→ Fired when a message arrives.onerror
→ Fired if there’s a connection error.onclose
→ Fired when the connection is closed.
Example:
socket.onopen = () => console.log("Connected!");
socket.onmessage = (e) => console.log("Received:", e.data);
socket.onerror = (e) => console.log("Error:", e);
socket.onclose = () => console.log("Connection closed");
Closing a WebSocket Connection
You can close a WebSocket connection using .close()
.
Example:
// Close manually
socket.close();
A close can be:
- Normal closure (done by client or server).
- Abnormal closure (due to network failure or server crash).
Error Handling in WebSockets
Errors may occur due to:
- Network issues
- Server not available
- Wrong URL
Example with error handling:
socket.onerror = function(event) {
console.log("WebSocket error observed:", event);
};
Reconnecting strategy (basic example):
socket.onclose = function() {
console.log("Connection closed. Reconnecting...");
setTimeout(() => {
socket = new WebSocket("ws://example.com/socket");
}, 3000);
};
WebSocket Security
- Always use
wss://
for secure communication (encrypted like HTTPS). - Follow same-origin policy (default security rule).
- Validate messages from the client to prevent attacks (e.g., injection).
Limitations of WebSockets
- Not always the best choice for simple apps (use AJAX instead).
- Proxies or firewalls may block WebSocket traffic.
- Uses server memory for persistent connections (scaling issues in very large apps).
Browser Support for WebSockets
Supported in all modern browsers:
- Chrome
- Firefox
- Safari
- Edge
- Opera
Not supported in very old browsers (IE < 10).
Always check support:
if ("WebSocket" in window) {
console.log("WebSockets are supported!");
} else {
console.log("Sorry, WebSockets not supported in this browser.");
}
Comparison with Other Technologies
- WebSockets vs AJAX (Polling)
- AJAX repeatedly requests new data → inefficient.
- WebSockets push data instantly → faster and real-time.
- WebSockets vs Server-Sent Events (SSE)
- SSE = one-way (server → client).
- WebSocket = two-way (client ↔ server).
Use SSE for live notifications/news feed.
Use WebSockets for chats, games, collaborative apps.