NodeJs — WebSockets with Socket.IO
WebSockets enable real-time, bi-directional communication between clients and the server. The 'socket.io' package is a popular library for implementing WebSockets in Node.js applications, ideal for chat apps or live notifications.
npm install socket.io
// server.js
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
io.on('connection', socket => {
console.log('A user connected');
socket.on('message', msg => {
io.emit('message', msg);
});
});
server.listen(3000);