Networking

What is WebSocket?

WebSocket is a communication protocol that provides full-duplex, bidirectional communication between a client and server over a single, long-lived TCP connection, enabling real-time data exchange without the overhead of repeated HTTP requests.

How Does WebSocket Work?

Traditional HTTP follows a request-response pattern: the client sends a request and waits for a response, then the connection is effectively idle until the next request. WebSocket upgrades an initial HTTP connection into a persistent, bidirectional channel where both the client and server can send messages to each other at any time without the overhead of new HTTP headers for each message. This makes it ideal for applications requiring real-time updates.

WebSocket connections begin with an HTTP handshake (the Upgrade request) and then switch to the WebSocket protocol. Common use cases include live chat applications, real-time notifications, collaborative editing (like Google Docs), online gaming, financial trading dashboards, and live sports updates. WebSocket servers can be built with libraries like Socket.IO (Node.js), ws (Node.js), or built-in support in frameworks like Django Channels and Spring WebFlux. The protocol operates on the same ports as HTTP (80) and HTTPS (443), making it firewall-friendly.