6

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
  }
})
Profer
  • 553
  • 8
  • 40
  • 81
  • Unclear question. Just can't tell what you are trying to do or what the problem is from this limited amount of code. Don't know what "app emit events multiple times" even means. You don't show any client code so we can see what it may be doing to connect multiple times or sending multiple messages. Also, it still looks like partial code because there are things inside the `.map()` loop that you never use. – jfriend00 May 23 '19 at 05:18
  • @jfriend00 Client code is on (swift)"IOS" platform. I do not know what they exactly do but I can explain you what I get in my logs. **Explanation:-** When I console inside my socket function I am getting the sockeId multiple times don't know why. I have read your comments on [this](https://stackoverflow.com/questions/44909405/socket-io-server-emits-multiple-times) and tried to understand what is happening. But the problem is mobile end only connects socket single time and I am getting console with `ids` multiple times. – Profer May 23 '19 at 05:49
  • @jfriend00 Yes but they written `socket.on` multiple times to catch different events. Is that something wrong with it? – Profer May 23 '19 at 05:49
  • @jfriend00 Ok final question. I have unique event on mobile end. Unique events are being created by unique mongodb `_id`. So why when I emit using `Socket.emit(_id, message)` does not emit the event? And when I do `io.emit` || `socket.broadcast.emit` it emits multiple times. **Question->** Socket emits on `event` or `listners`. Please reply to this. – Profer May 23 '19 at 08:05

2 Answers2

1

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.

aron.duby
  • 2,072
  • 2
  • 15
  • 21
0

use io.to(messageSocket${member.memberId}).emit() instead of socket.broadcast.emit()