WebSockets are a communication protocol that keeps a connection open between a client and a server so both sides can send messages at any time.
They are commonly used for:
- Real-time chat
- Live notifications
- Multiplayer games
- Collaborative editing
- Dashboard updates
WebSockets start with an HTTP upgrade request, then switch to a persistent bidirectional connection.
JavaScript example
In the browser, you create a WebSocket and listen for events:
const socket = new WebSocket("wss://example.com/chat");
socket.addEventListener("open", () => {
socket.send(JSON.stringify({ type: "join", room: "general" }));
});
socket.addEventListener("message", (event) => {
const payload = JSON.parse(event.data);
console.log("Received:", payload);
});
socket.addEventListener("close", () => {
console.log("Connection closed");
});This shows the basic pattern:
openmeans the connection is readysend()transmits a message to the servermessagereceives data from the serverclosehandles disconnects
Conceptual links
WebSockets are the transport layer underneath systems like Phoenix Framework, where they support real-time message passing. They are often paired with Concurrent Programming and Actor Model style designs.