Home > other >  Notification with socket.io. NodeJS
Notification with socket.io. NodeJS

Time:06-19

So, I'm trying to make a notification system but I'm running into a problem.

I sent a invitation to a user to join the club.

socket.on("notify", async (message) => {
  // invite the user John Doe
  io.to('socket.id of John Doe').emit('notificaton', msg);
});

Question

But how do I get the socket.id of John Doe to emit the invitation notification to him?

John Doe receives the message after refreshing the page, which gets the notification from database. But I don't want John Doe to refresh every time to check his notification. I want it to be in real time. But to send him the notification in real time, I can only think of one thing and that is to store the socket.id of John Doe in database and update that every time John Doe login to the application, which might cause a problem if John Doe has logged on to multiple devices with same account cuz the socket.id might be different in other devices. And only one of his device receives the notification. * I don't know if socket.id is different for every devices when logged on with multiple devices *

Can you please help me to come up with a better solution ?

CodePudding user response:

Usually, one keeps the socket in some in-memory data structure (such as a Map object) where a userID is the key and the current socket for that user is the data. Then, you can look up any user's socket with their userID and internal to your app, you use your userID (a persistent thing not tied to socket.io) to identify the user. Then, you can look up any user's socket at any time (if they are currently connected).

When a user connects, you add their socket to the Map object and when they disconnect, you remove it. You can also make sure that both client and server ends of the socket.io connection know which userID they represent.

Note, you cannot store a socket object in your database as it's a live object that includes native code state that can't be directly stored in a database. You would store a socket.id which is just a string in a database, but usually you would just maintain an in-memory data structure for currently connected users.

  • Related