Your Essential Queries
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:
- const express = require('express');
- const http = require('http');
- const socketIo = require('socket.io');
- const app = express();
- const server = http.createServer(app);
- const io = socketIo(server);
- const users = new Map();
- io.on('connection', socket => {
- console.log(`New client connected: ${socket.id}`);
- socket.on('join_room', room => {
- console.log(`Client joined room: ${room}`);
- socket.join(room);
- users.set(socket.id, room);
- });
- socket.on('send_notification', notification => {
- console.log(`Received notification: ${notification}`);
- const room = users.get(socket.id);
- socket.broadcast.to(room).emit('receive_notification', notification);
- });
- socket.on('disconnect', () => {
- console.log(`Client disconnected: ${socket.id}`);
- const room = users.get(socket.id);
- socket.leave(room);
- users.delete(socket.id);
- });
- });
- const PORT = process.env.PORT || 3000;
- server.listen(PORT, () => {
- console.log(`Server listening on port ${PORT}`);
- });
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.