WebSocket is a protocol that enables full-duplex, real-time communication between a client and a server over a single persistent connection. Unlike traditional HTTP request-response models, WebSockets allow data to be pushed instantly from server to client. This makes WebSockets ideal for chat applications, live notifications, real-time dashboards, and multiplayer games.
A WebSocket connection starts as an HTTP handshake and then upgrades to the WebSocket protocol. Once connected, both client and server can send messages independently. WebSocket URLs use ws:// or wss:// (secure).
// Creating a new WebSocket connection
const socket = new WebSocket("wss://echo.websocket.org");
// Event triggered when connection opens
socket.onopen = () => {
socket.send("Hello WebSocket");
};
// Event triggered when message is received
socket.onmessage = (event) => {
console.log(event.data);
};
// Event triggered when connection closes
socket.onclose = () => {
console.log("Connection closed");
};
When the connection opens, the client sends a message to the server. The server echoes the message back, which is then logged in the console. The connection remains open until explicitly closed.
Client ➜ WebSocket Handshake ➜ Persistent Connection ➜ Real-Time Messages ➜ Client
This flow demonstrates how data travels instantly without repeated HTTP requests.
wss) in production