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.
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.
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);
});
});
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);
});
Let's take a look at a few more examples.
wss.on('connection', (ws) => {
ws.on('message', (message) => {
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(`Broadcast: ${message}`);
}
});
});
});
ws.on('close', () => {
console.log('Client disconnected');
});
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:
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);