Let's build a practical example of a real-time application using Socket.IO—a collaborative drawing board where multiple users can draw on a shared canvas in real time.
Socket.IO
to broadcast drawing events to all connected clients in real-time.
mkdir collaborative-drawing
cd collaborative-drawing
npm init -y
npm install express socket.io
collaborative-drawing/
├── index.html
├── public/
│ └── script.js
└── server.js
This file will set up the Express server and integrate Socket.IO to handle real-time communication.
// File: server.js
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
// Initialize Express
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
// Serve static files from the "public" directory
app.use(express.static('public'));
// Handle new WebSocket connections
io.on('connection', (socket) => {
console.log('A user connected');
// Broadcast the drawing data to all other clients
socket.on('drawing', (data) => {
socket.broadcast.emit('drawing', data);
});
// Handle user disconnection
socket.on('disconnect', () => {
console.log('A user disconnected');
});
});
// Start the server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
HTML File (index.html
): This file will create the basic structure of the web page.
Collaborative Drawing Board
JavaScript File (script.js
): This file contains the logic for drawing on the canvas and sending the drawing data to the server.
// File: public/script.js
const socket = io();
// Get the canvas element and its context
const canvas = document.getElementById('drawing-board');
const context = canvas.getContext('2d');
// Set canvas size
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Set initial state
let drawing = false;
let current = {
x: 0,
y: 0
};
// Handle mouse events
canvas.addEventListener('mousedown', onMouseDown, false);
canvas.addEventListener('mouseup', onMouseUp, false);
canvas.addEventListener('mouseout', onMouseUp, false);
canvas.addEventListener('mousemove', onMouseMove, false);
// Draw on the canvas
function drawLine(x0, y0, x1, y1, color = 'black', emit = true) {
context.beginPath();
context.moveTo(x0, y0);
context.lineTo(x1, y1);
context.strokeStyle = color;
context.lineWidth = 2;
context.stroke();
context.closePath();
if (!emit) return;
const w = canvas.width;
const h = canvas.height;
// Emit the drawing event to the server
socket.emit('drawing', {
x0: x0 / w,
y0: y0 / h,
x1: x1 / w,
y1: y1 / h,
color: color
});
}
// Mouse event handlers
function onMouseDown(e) {
drawing = true;
current.x = e.clientX;
current.y = e.clientY;
}
function onMouseUp(e) {
if (!drawing) return;
drawing = false;
drawLine(current.x, current.y, e.clientX, e.clientY);
}
function onMouseMove(e) {
if (!drawing) return;
drawLine(current.x, current.y, e.clientX, e.clientY);
current.x = e.clientX;
current.y = e.clientY;
}
// Listen for drawing events from the server
socket.on('drawing', (data) => {
const w = canvas.width;
const h = canvas.height;
drawLine(data.x0 * w, data.y0 * h, data.x1 * w, data.y1 * h, data.color, false);
});
node server.js
Access the Application: Open your browser and navigate to http://localhost:3000
. Open multiple browser windows or tabs to simulate multiple users.
Server-Side: The server listens for incoming WebSocket connections. When a client sends a drawing event, the server broadcasts this event to all other connected clients. This ensures that all users see the same drawing in real time.
Client-Side: Users can draw on the canvas using their mouse. The drawing data (starting and ending coordinates of the line) is sent to the server, which then relays this data to all other clients. Each client listens for incoming drawing events and updates its canvas accordingly.
This practical example demonstrates the power of Socket.IO in building real-time applications. By implementing a collaborative drawing board, you've seen how easy it is to synchronize data between multiple clients in real time. This approach can be extended to build various other real-time applications, such as chat apps, multiplayer games, or live data dashboards.Happy coding !❤️