WebSockets is a powerful technology that allows for real-time, bidirectional communication between a client (usually a browser) and a server over a single, long-lived connection. Unlike traditional HTTP, which requires multiple requests and responses to send and receive data, WebSockets establish a continuous connection, enabling seamless data exchange with minimal latency. This makes WebSockets ideal for applications that require frequent data updates, such as chat apps, online gaming, live sports scores, and financial dashboards.
In this chapter, we’ll dive deep into the basics of WebSockets, how to use them in HTML and JavaScript, and practical examples to help you implement WebSockets in your own web applications.
WebSockets is a protocol that provides a full-duplex communication channel over a single, persistent connection between a client and a server. This means data can be sent and received simultaneously, unlike HTTP, which follows a request-response model.
Key Features of WebSockets:
The lifecycle of a WebSocket connection includes:
In HTML5, WebSockets are typically implemented using JavaScript and the WebSocket
API, which allows for easy connection management and message handling.
To create a WebSocket connection, you first create an instance of the WebSocket
object in JavaScript, specifying the server URL.
// Initializing a new WebSocket
const socket = new WebSocket('ws://echo.websocket.org');
// Event listener for when the connection opens
socket.addEventListener('open', (event) => {
console.log('Connection opened');
socket.send('Hello Server!'); // Sending a message to the server
});
// Event listener for incoming messages
socket.addEventListener('message', (event) => {
console.log('Message from server:', event.data);
});
// Event listener for when the connection closes
socket.addEventListener('close', (event) => {
console.log('Connection closed');
});
new WebSocket(url)
: Initializes a WebSocket connection. Here, we’re connecting to ws://echo.websocket.org
, a public echo server.socket.addEventListener('open')
: Triggered when the connection opens. We can send a message right after the connection is established.socket.send(message)
: Sends a message to the server.socket.addEventListener('message')
: Listens for messages from the server and logs them.socket.addEventListener('close')
: Triggered when the connection is closed, either by the client or server.Output: The client sends “Hello Server!” to the server, which echoes it back. The client then receives this message and logs it.
WebSocket messages can be sent as:
// Sending a text message
socket.send('This is a text message');
// Sending a binary message (ArrayBuffer)
const buffer = new ArrayBuffer(8);
const view = new DataView(buffer);
view.setInt32(0, 100);
socket.send(buffer);
WebSocket supports four main events:
open
: Triggered when a WebSocket connection is successfully opened.message
: Triggered when a message is received from the server.close
: Triggered when the WebSocket connection is closed.error
: Triggered when there is an error with the WebSocket connection.
socket.onopen = function() {
console.log('Connection established');
};
socket.onmessage = function(event) {
console.log('Received:', event.data);
};
socket.onclose = function() {
console.log('Connection closed');
};
socket.onerror = function(error) {
console.log('WebSocket Error:', error);
};
To understand WebSockets better, let’s build a basic chat application where users can send and receive messages in real-time.
WebSocket Chat
WebSocket Chat
chatSocket
: Establishes a WebSocket connection to the server.chatSocket.onmessage
: Appends incoming messages to the chat box.sendMessage()
: Sends the typed message to the server and clears the input.In this application, when users type a message and click “Send,” the message is sent to the server and broadcasted back to all clients. The chatBox
will display each message as it arrives.
For the chat application to work, we also need a server to handle WebSocket connections. Below is a simple Node.js WebSocket server using the ws
library.
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', (socket) => {
console.log('A user connected');
// Broadcast messages to all connected clients
socket.on('message', (message) => {
console.log('Received:', message);
server.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
// Notify when a user disconnects
socket.on('close', () => {
console.log('A user disconnected');
});
});
8080
.To use WebSockets securely:
wss://
instead of ws://
.WebSockets offer a robust solution for real-time, bidirectional communication between clients and servers. By using a single, persistent connection, WebSockets reduce the overhead associated with HTTP requests and are ideal for interactive, data-driven applications like chat apps, gaming, and live updates. With WebSocket support across modern browsers and simple APIs, it has become an essential tool for creating dynamic, real-time web applications. Happy coding !❤️