Express.js / Express.js and WebSockets
Handling Real-Time Communication with WebSockets
This tutorial provides a deep dive into handling real-time communication with WebSockets, enabling you to create interactive and responsive web applications.
Section overview
5 resourcesCovers integrating WebSockets for real-time communication in Express applications.
Introduction
The goal of this tutorial is to provide an in-depth understanding of how to use WebSockets for real-time communication in your web applications. By the end of this tutorial, you'll be able to build a simple chat application that can send and receive messages in real-time.
Prerequisites include basic knowledge of JavaScript, HTML, and Node.js. Familiarity with Express.js will also be beneficial but is not a requirement.
Step-by-Step Guide
WebSockets is a protocol that provides full-duplex communication channels over a single TCP connection. It allows servers to push updates to clients as they happen, leading to efficient real-time communication.
Creating a WebSocket Server
We'll be using Node.js and Express.js to create a WebSocket server. First, install the necessary dependencies:
npm install express ws
Here is a simple WebSocket server:
const express = require('express');
const WebSocket = require('ws');
const app = express();
const PORT = 3000;
const wss = new WebSocket.Server({ noServer: true });
wss.on('connection', (ws) => {
ws.on('message', (message) => {
console.log('Received: ', message);
ws.send(`Server response: ${message}`);
});
ws.send('Hello from server!');
});
const server = app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
server.on('upgrade', (request, socket, head) => {
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request);
});
});
Creating a WebSocket Client
On the client-side, we can create a WebSocket connection to our server:
const socket = new WebSocket('ws://localhost:3000');
socket.addEventListener('open', (event) => {
socket.send('Hello Server!');
});
socket.addEventListener('message', (event) => {
console.log('Message from server: ', event.data);
});
Code Examples
Let's take a look at a few more examples.
- Broadcasting messages to all connected clients
wss.on('connection', (ws) => {
ws.on('message', (message) => {
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(`Broadcast: ${message}`);
}
});
});
});
- Handling close events
ws.on('close', () => {
console.log('Client disconnected');
});
Summary
In this tutorial, we've learned how to create a WebSocket server and client, and how to handle messages and events. Next, you could explore more about handling different types of data, such as binary data or JSON.
You may find the following resources helpful:
Practice Exercises
- Simple Echo Server: Create a WebSocket server that sends back any message it receives.
- Chat Application: Extend the echo server to broadcast messages to all connected clients.
- Real-time Updates: Create an application that sends real-time updates from the server to the client, such as a simple clock that sends the current time every second.
Here's a hint for the third exercise: you can use JavaScript's setInterval function to send a message every second:
setInterval(() => {
ws.send(`The time is ${new Date()}`);
}, 1000);
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article