KenoKivabe

Your Essential Queries

Author
Md Mojahedul Islam
31 Jan, 2023

Nodejs Setting Up Push Notifications Using Socket.IO



Node.js setting up push notifications using Socket.IO, with additional features such as handling multiple rooms and broadcast to specific rooms:

  1. const express = require('express');  
  2. const http = require('http');  
  3. const socketIo = require('socket.io');  
  4.   
  5. const app = express();  
  6. const server = http.createServer(app);  
  7. const io = socketIo(server);  
  8.   
  9. const users = new Map();  
  10.   
  11. io.on('connection', socket => {  
  12.   console.log(`New client connected: ${socket.id}`);  
  13.   
  14.   socket.on('join_room', room => {  
  15.     console.log(`Client joined room: ${room}`);  
  16.   
  17.     socket.join(room);  
  18.     users.set(socket.id, room);  
  19.   });  
  20.   
  21.   socket.on('send_notification', notification => {  
  22.     console.log(`Received notification: ${notification}`);  
  23.   
  24.     const room = users.get(socket.id);  
  25.     socket.broadcast.to(room).emit('receive_notification', notification);  
  26.   });  
  27.   
  28.   socket.on('disconnect', () => {  
  29.     console.log(`Client disconnected: ${socket.id}`);  
  30.   
  31.     const room = users.get(socket.id);  
  32.     socket.leave(room);  
  33.     users.delete(socket.id);  
  34.   });  
  35. });  
  36.   
  37. const PORT = process.env.PORT || 3000;  
  38. server.listen(PORT, () => {  
  39.   console.log(`Server listening on port ${PORT}`);  
  40. });  

This code extends the basic Socket.IO setup by adding the capability to handle multiple rooms. When a client connects, it can join a specific room using the join_room event. The server will then keep track of the client's room in a Map object. When a notification is received, the server will broadcast the notification to all clients in the same room using the broadcast.to method. When a client disconnects, the server will remove the client's information from the Map object and leave the room.

Share: