多次插座发射事件 [英] Socket emitting event multiple times

查看:94
本文介绍了多次插座发射事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用socket进行聊天。这是我在nodejs文件中的套接字代码,它运行良好。

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

外部套接字 io.emit 工作正常,向连接到 conversationId 的所有用户发出消息。

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

但是 socket.broadcast.emit (当用户使用应用程序时)我用来通知用户,发出( socket.broadcast.emit )事件多个倍。为什么会这样?我是否完全错过套接字方法。

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
  }
})


推荐答案

来自广播文档:


为后续事件发射设置一个修饰符,事件数据
只会广播到发送者的每个套接字。

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

所以在你的循环中你是说除了原始套接字之外发送给所有人,你多次调用它。您想要使用它 it.to

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)

从你的例子中不清楚是否 messageSocket $ {member.memberId} 应该是您指定的 socket.id 的事件名称。

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.

这是这个 https://的绝佳备忘单socket.io/docs/emit-cheatsheet/

附注,如果您获取会员ID的api电话很重要,那么您可能最好使用房间/ namespace并在connect上执行该查询以确定房间。

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.

这篇关于多次插座发射事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆