Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket emitting event multiple times

I am working on socket for chatting. Here is my socket code in nodejs file which is working well.

The outer socket io.emit working good and emits the message to all the users which are connected to that conversationId.

But the socket.broadcast.emit(when user uses the app) which I am using to notify user, emits(socket.broadcast.emit) events multiple times. Why this is happening? Am I completely missing the socket approach.

socket.on('sendMessage', async(action2) => {
  try {
    action2.author = socket.decoded.id
    action2.readBy = [socket.decoded.id]
    action2.deliveredTo = [socket.decoded.id]
    const createMessage = await Message.create(action2)

    const sender = await User.findOne({ _id: socket.decoded.id }, { firstName: 1 })

    const memebers = //some api call to get members
    const promises = members.map(async(member) => {
      // socket for message
      const socketNotification = {
        // my object
      }
      console.log(socketNotification, 'socketNotifcication')
      socket.broadcast.emit(`messageSocket${member.memberId}`, socketNotification)
    })
    await Promise.all(promises)
    io.emit(action2.conversationId, messages) // "newMessage"
  } catch (err) {
    throw err
  }
})
like image 935
Profer Avatar asked May 22 '19 10:05

Profer


1 Answers

From the Broadcast docs:

Sets a modifier for a subsequent event emission that the event data will only be broadcast to every sockets but the sender.

https://socket.io/docs/server-api/#Flag-%E2%80%98broadcast%E2%80%99

So in your loop you are saying send this everyone but the original socket, and you call that multiple times. What you want to use it it.to

io.to(membersSocketID).emit('eventName', socketNotification)

It's unclear from your example if the messageSocket${member.memberId} is supposed to be the event name of if that is your specified socket.id.

This is a great cheatsheet for this https://socket.io/docs/emit-cheatsheet/

Side note, if your api call to get the member id's is significant you might be better off using rooms/namespaces and doing that query on connect to determine rooms.

like image 105
aron.duby Avatar answered Oct 19 '22 11:10

aron.duby