【问题标题】:Broadcasting to everyone except sender socket.io向除发送者 socket.io 之外的所有人广播
【发布时间】:2023-02-01 13:47:57
【问题描述】:

我正在我的应用程序中建立聊天。我为此使用 socket.io。当用户发送一条消息时,我会向我的服务器发送一个 api 请求。 api 将消息存储在数据库中,然后才发出,通过套接字服务向房间中的每个人发送一条新消息。我有一个使用此方法的 SocketService 类:

  private async broadcast({ type, data, chatId, senderId }: { type: string; data: any; chatId: string; senderId: string }) {
const excludedSocket = await this.getUserSocket(senderId);
if (chatId && excludedSocket) {
  excludedSocket.emit;
} else if (excludedSocket) {
  excludedSocket.emit(type, data);
} else if (room) {
  gIo.to(room).emit(type, data);
} else {
  gIo.emit(type, data);
}

}

我遇到的问题是 getUserSocket 返回一个没有广播或方法的 RemoteSocket 对象。那么我该如何实现呢?

 private async getUserSocket(userId: string) {
const sockets = await this.getAllSockets();
const socket = sockets.find((s) => s.data.uid === userId);
return socket;

}

private async getAllSockets() {
const sockets = await this.io.fetchSockets();
return sockets

}

【问题讨论】:

    标签: javascript node.js sockets socket.io broadcast


    【解决方案1】:

    socket.broadcast.emit 等同于发送到一组空房间(意思是“所有房间”)的 BroadcastOperator,不包括发送方套接字的套接字 ID“房间”。

    可以使用 server.except() 从服务器实例创建相同的 BroadcastOperator

    const sockets = await this.io.except(socketIdString).emit('blah', x)
    

    【讨论】:

    • 但我想发送到一个特定的房间,这是 chatId,并且只排除发件人。除了将房间作为参数,而不是套接字 ID
    • 密码是this.io.to(room).except(xroom).emit('blah', x)。如果您没有 except 的套接字 ID,那么您需要一个房间,或者以其他方式查找您想要 except 的 id。
    【解决方案2】:

    您需要检索您想要发送给除发件人以外的所有人的特定套接字(这是发送消息的套接字)

     io.fetchSockets().then((clients) => {
        
        clients.map(client => {
          if(client.id === senderId){
            client.to(roomId).emit(type,data)
          }
        })
      });
    

    或者看到您正在尝试为您的应用程序构建聊天功能,我建议您使用第三方服务,如MinChat

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-26
      • 1970-01-01
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      • 2013-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多