【问题标题】:Send message to all connected clients socket.io向所有连接的客户端发送消息 socket.io
【发布时间】:2019-08-04 07:08:05
【问题描述】:

我正在使用下面的代码将消息发送到特定的客户端 sessionId。

this.sockets[sessionId].json().send(message)

但我不知道,如何向所有连接的客户端(浏览器)发送消息而不是发送给一个。

【问题讨论】:

    标签: websocket socket.io


    【解决方案1】:

    查看此备忘单

    仅发送到发送者客户端

    socket.emit('message', "this is a test");
    

    发送给所有客户端,包括发件人

    io.emit('message', "this is a test");
    

    发送给除发件人以外的所有客户端

    socket.broadcast.emit('message', "this is a test");
    

    发送到“游戏”房间(频道)中的所有客户端,发送者除外

    socket.broadcast.to('game').emit('message', 'nice game');
    

    发送给“游戏”房间(频道)中的所有客户端,包括发送者

    io.in('game').emit('message', 'cool game');
    

    发送给发送者客户端,仅当他们在“游戏”房间(频道)中时

    socket.to('game').emit('message', 'enjoy the game');
    

    发送到命名空间“myNamespace”中的所有客户端,包括发件人

    io.of('myNamespace').emit('message', 'gg');
    

    发送到单独的socketid

    socket.broadcast.to(socketid).emit('message', 'for your eyes only');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-18
      • 1970-01-01
      • 2017-07-01
      • 2018-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-29
      相关资源
      最近更新 更多