WebSockets

For real-time communication, you can use WebSockets with the ws library or socket.io.

a. Install Socket.IO

npm install socket.io

b. Set Up Socket.IO

In app.js:

const http = require('http');
const socketIo = require('socket.io');
const server = http.createServer(app);
const io = socketIo(server);

io.on('connection', (socket) => {
  console.log('A user connected');
  socket.on('disconnect', () => {
    console.log('User disconnected');
  });
});

server.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *