Clean β’ Professional
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.
ws:// or secure wss://).Key point:
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).
Once the connection is open, you can:
.send()..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).
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");You can close a WebSocket connection using .close().
Example:
// Close manually
socket.close();A close can be:
Errors may occur due to:
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);
};wss:// for secure communication (encrypted like HTTPS).Supported in all modern browsers:
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.");
}Use SSE for live notifications/news feed.
Use WebSockets for chats, games, collaborative apps.