Websockets are a communication protocol used to build real-time features by establishing a two-way connection between a client and a server.
Imagine an online multiplayer game where the leaderboard updates instantly as players score points, showing real-time rankings of all players.
This instantaneous update feels seamless and keeps you engaged, but how does it actually work?
The magic behind this real-time experience is often powered by WebSockets.
WebSockets enable full-duplex, bidirectional communication between a client (typically a web browser) and a server over a single TCP connection.
Unlike the traditional HTTP protocol, where the client sends a request to the server and waits for a response, WebSockets allow both the client and server to send messages to each other independently and continuously after the connection is established.
In this chapter, we will explore how websockets work, why/where are they used, how it compares with other communication methods, challenges and considerations and how to implement them in code.
The WebSocket connection starts with a standard HTTP request from the client to the server.
However, instead of completing the request and closing the connection, the server responds with an HTTP 101 status code, indicating that the protocol is switching to WebSockets.
After this handshake, a WebSocket connection is established, and both the client and server can send messages to each other over the open connection.
The client initiates a connection request using a standard HTTP GET request with an "Upgrade" header set to "websocket".
If the server supports WebSockets and accepts the request, it responds with a special 101 status code, indicating that the protocol will be changed to WebSocket.
Once the handshake is complete, the WebSocket connection is established. This connection remains open until explicitly closed by either the client or the server.
Both the client and server can now send and receive messages in real-time.
These messages are sent in small packets called frames, and carry minimal overhead compared to traditional HTTP requests.
The connection can be closed at any time by either the client or server, typically with a "close" frame indicating the reason for closure.
WebSockets offer several advantages that make them ideal for certain types of applications:
To understand the advantages of WebSockets, it's helpful to compare them with other communication methods:
While WebSockets offer numerous benefits, there are some challenges to consider:
Applications like Google Docs may use WebSockets to enable multiple users to edit a document simultaneously. Changes made by one user are instantly reflected for all others, creating a seamless collaborative experience.
One of the most popular uses of WebSockets is in real-time chat applications.
Messaging platforms like Slack use WebSockets to deliver messages instantly. This allows for real-time conversations and immediate message delivery notifications.
Social media platforms use WebSockets to push real-time notifications to users when they receive a new message, like, or comment.
Instead of the client constantly checking for new notifications, the server can push updates to the client as soon as they occur.
In online multiplayer games, low latency is crucial for a seamless gaming experience.
WebSockets provide the necessary real-time communication between the game server and players, ensuring that all players see the same game state simultaneously.
WebSockets are widely used in financial applications to stream real-time market data, such as stock prices, forex rates, and cryptocurrency values.
In IoT applications, devices often need to communicate with a server in real time.
WebSockets provide a lightweight and efficient communication channel for sending sensor data, receiving commands, and synchronizing device states.
While the actual video streaming typically uses other protocols, WebSockets can be used for real-time chat, viewer counts, and other interactive features during live broadcasts.
To demonstrate how WebSockets work, let’s look at a simple implementation using Node.js on the server side and JavaScript on the client side.
WebSockets have revolutionized how we build real-time web applications, providing an efficient, low-latency communication channel that supports full-duplex data exchange.
From chat applications and live notifications to online gaming and IoT devices, WebSockets enable the creation of responsive and engaging user experiences.
However, with great power comes great responsibility. Implementing WebSockets requires careful consideration of scalability, security, and resource management to ensure your application performs well under all conditions.