Understand the event-driven nature of websockets and how they can be used for bidirectional communication between clients and servers. Implement applications that exchange messages using the WebSocket protocol.
Examples
Exercises
Context
In a distributed system, multiple systems must communicate with one another. On the web, a client (e.g. a browser or a server) wants to communicate with a server (e.g. a web service). To facilitate this, the server provides an application programming interface (API). These APIs can be implemented using various architectural styles and technologies.
An event-driven architecture is a type of software architecture that is based on producing, detecting and responding to events. Whenever something significant occurs, clients emit an event. Depending on the type of server, the event is either dispatched to all participants (Relay), a few interested participants (Publish-Subscribe) or a single recipient (Queue).
In the following example, Alice has placed an order with the ID 5
. She notifies other participants of the system, by sending an event ****with a unique id 69688550-5be2-41e4-a057-b9da2d59eb03
and event type order_placed
. Bob checks every placed order and confirmes it, if valid, with an order_confirmed
event.
The initial event at 1 sent by Alice could look like this:
{
"id": "69688550-5be2-41e4-a057-b9da2d59eb03",
"type": "order_placed",
"created": "1676554735324",
"source": "alice",
"data": {
"id": 5
}
}
WebSockets is an application protocol that provides a bidirectional communication channel over a single TCP connection. It enables near real-time, two-way communication between a client and a server. Both the client and the server can send data at any time, without having to wait for a response. This makes it ideal for applications that require frequent updates, such as data streaming and gaming.
The protocol is standardized and maintained by the Internet Engineering Task Force (IETF):
RFC ft-ietf-hybi-thewebsocketprotocol: The WebSocket Protocol
Since around 2011, all major browsers support WebSockets out-of-the-box:
The following example demonstrates how to use WebSockets from a browser:
// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');
// Connection opened
socket.addEventListener('open', (event) => {
socket.send('Hello Server!');
});
// Listen for messages
socket.addEventListener('message', (event) => {
console.log('Message from server ', event.data);
});
The protocol works with existing infrastructure over HTTP ports 80 and 443, so there is no need to change firewall rules. It begins as a normal HTTP request and is then upgraded with a handshake.