In this tutorial, we'll learn how to build real-time web applications using WebSockets in Node.js. WebSockets provide full-duplex communication channels over a single TCP connection.
Node.js Real-Time with WebSockets
1. Setting Up WebSocket Server with `ws`
We will start by installing the WebSocket library and setting up a basic server that listens for incoming WebSocket connections.
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
ws.on('message', (message) => {
console.log(`Received: ${message}`);
});
ws.send('Hello! You are connected');
});
This basic WebSocket server listens on port 8080 and sends a welcome message to each new client.
2. Handling Real-Time Communication
Now, we can handle real-time messages sent by the client and broadcast 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(message);
}
});
});
});
This code listens for messages from clients and broadcasts them to all other connected clients.
3. Real-Time Client-Side Integration
Next, we will write the client-side code to connect to the WebSocket server and send/receive messages in real-time.
const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('open', () => {
socket.send('Hello Server!');
});
socket.addEventListener('message', (event) => {
console.log(`Message from server: ${event.data}`);
});
This client-side code connects to the WebSocket server and sends a message once the connection is open. It also listens for messages from the server.