【问题标题】:Send response to all clients except sender向除发件人以外的所有客户端发送响应
【发布时间】:2012-04-20 22:36:00
【问题描述】:

要将某些内容发送给所有客户端,请使用:

io.sockets.emit('response', data);

要从客户那里接收,您使用:

socket.on('cursor', function(data) {
  ...
});

如何将两者结合起来,以便在服务器上从客户端接收消息时,将该消息发送给除发送消息的用户之外的所有用户?

socket.on('cursor', function(data) {
  io.sockets.emit('response', data);
});

我是否必须通过发送带有消息的客户端 ID 然后检查客户端来破解它,还是有更简单的方法?

【问题讨论】:

    标签: javascript node.js socket.io


    【解决方案1】:

    针对 Socket.io v4.0.0+ 更新

    要在 v4 中向除发件人之外的所有客户端发出,请使用:

    socket.broadcast.emit(/* ... */);
    

    示例用法

    io.on("connection", (socket) => {
       socket.on("message", (message) => {
          //sends "newMessage" to all sockets except sender
          socket.broadcast.emit("newMessage", message)
       })
    })
    

    【讨论】:

      【解决方案2】:

      V4.x 中服务器端所有有效的发出事件列表

      io.on("connection", (socket) => {
      
      // basic emit
      socket.emit(/* ... */);
      
      // to all clients in the current namespace except the sender
      socket.broadcast.emit(/* ... */);
      
      // to all clients in room1 except the sender
      socket.to("room1").emit(/* ... */);
      
      // to all clients in room1 and/or room2 except the sender
      socket.to(["room1", "room2"]).emit(/* ... */);
      
      // to all clients in room1
      io.in("room1").emit(/* ... */);
      
      // to all clients in room1 and/or room2 except those in room3
      io.to(["room1", "room2"]).except("room3").emit(/* ... */);
      
      // to all clients in namespace "myNamespace"
      io.of("myNamespace").emit(/* ... */);
      
      // to all clients in room1 in namespace "myNamespace"
      io.of("myNamespace").to("room1").emit(/* ... */);
      
      // to individual socketid (private message)
      io.to(socketId).emit(/* ... */);
      
      // to all clients on this node (when using multiple nodes)
      io.local.emit(/* ... */);
      
      // to all connected clients
      io.emit(/* ... */);
      
      // WARNING: `socket.to(socket.id).emit()` will NOT work, as it will send to everyone in the room
      // named `socket.id` but the sender. Please use the classic `socket.emit()` instead.
      
      // with acknowledgement
      socket.emit("question", (answer) => {
          // ...
      });
      
      // without compression
      socket.compress(false).emit(/* ... */);
      
      // a message that might be dropped if the low-level transport is not writable
      socket.volatile.emit(/* ... */);
      
      });
      

      客户端

      // basic emit
          socket.emit(/* ... */);
      
      // with acknowledgement
          socket.emit("question", (answer) => {
              // ...
          });
      
      // without compression
          socket.compress(false).emit(/* ... */);
      
      // a message that might be dropped if the low-level transport is not writable
          socket.volatile.emit(/* ... */);
      

      源链接存档 => http://archive.today/2021.06.22-023900/https://socket.io/docs/v4/emit-cheatsheet/index.html

      【讨论】:

        【解决方案3】:

        这是我的清单(更新到 1.0)

        // sending to sender-client only
        socket.emit('message', "this is a test");
        
        // sending to all clients, include sender
        io.emit('message', "this is a test");
        
        // sending to all clients except sender
        socket.broadcast.emit('message', "this is a test");
        
        // sending to all clients in 'game' room(channel) except sender
        socket.broadcast.to('game').emit('message', 'nice game');
        
        // sending to all clients in 'game' room(channel), include sender
        io.in('game').emit('message', 'cool game');
        
        // sending to sender client, only if they are in 'game' room(channel)
        socket.to('game').emit('message', 'enjoy the game');
        
        // sending to all clients in namespace 'myNamespace', include sender
        io.of('myNamespace').emit('message', 'gg');
        
        // sending to individual socketid
        socket.broadcast.to(socketid).emit('message', 'for your eyes only');
        
        // list socketid
        for (var socketid in io.sockets.sockets) {}
         OR
        Object.keys(io.sockets.sockets).forEach((socketid) => {});
        

        【讨论】:

        • 您愿意将此贡献给the FAQ吗?或者我可以为你做吗? (我会在这里提供一个反向链接)
        • 我没有io here.only socket
        • 作为// sending to all clients except sender的补充,// sending a response to sender client only的用途是什么?
        • 能否请您根据socket#insocket.to('others').emit('an event', { some: 'data' }); 以及房间中的广播添加。
        • 这比 socket.io 文档中的所有内容组合起来更有用
        【解决方案4】:

        发送备忘单

        io.on('connect', onConnect);
        
        function onConnect(socket){
        
          // sending to the client
          socket.emit('hello', 'can you hear me?', 1, 2, 'abc');
        
          // sending to all clients except sender
          socket.broadcast.emit('broadcast', 'hello friends!');
        
          // sending to all clients in 'game' room except sender
          socket.to('game').emit('nice game', "let's play a game");
        
          // sending to all clients in 'game1' and/or in 'game2' room, except sender
          socket.to('game1').to('game2').emit('nice game', "let's play a game (too)");
        
          // sending to all clients in 'game' room, including sender
          io.in('game').emit('big-announcement', 'the game will start soon');
        
          // sending to all clients in namespace 'myNamespace', including sender
          io.of('myNamespace').emit('bigger-announcement', 'the tournament will start soon');
        
          // sending to individual socketid (private message)
          socket.to(<socketid>).emit('hey', 'I just met you');
        
          // sending with acknowledgement
          socket.emit('question', 'do you think so?', function (answer) {});
        
          // sending without compression
          socket.compress(false).emit('uncompressed', "that's rough");
        
          // sending a message that might be dropped if the client is not ready to receive messages
          socket.volatile.emit('maybe', 'do you really need it?');
        
          // sending to all clients on this node (when using multiple nodes)
          io.local.emit('hi', 'my lovely babies');
        
        };
        

        【讨论】:

          【解决方案5】:

          更新了列表以获取更多文档。

          socket.emit('message', "this is a test"); //sending to sender-client only
          socket.broadcast.emit('message', "this is a test"); //sending to all clients except sender
          socket.broadcast.to('game').emit('message', 'nice game'); //sending to all clients in 'game' room(channel) except sender
          socket.to('game').emit('message', 'enjoy the game'); //sending to sender client, only if they are in 'game' room(channel)
          socket.broadcast.to(socketid).emit('message', 'for your eyes only'); //sending to individual socketid
          io.emit('message', "this is a test"); //sending to all clients, include sender
          io.in('game').emit('message', 'cool game'); //sending to all clients in 'game' room(channel), include sender
          io.of('myNamespace').emit('message', 'gg'); //sending to all clients in namespace 'myNamespace', include sender
          socket.emit(); //send to all connected clients
          socket.broadcast.emit(); //send to all connected clients except the one that sent the message
          socket.on(); //event listener, can be called on client to execute on server
          io.sockets.socket(); //for emiting to specific clients
          io.sockets.emit(); //send to all connected clients (same as socket.emit)
          io.sockets.on() ; //initial connection from a client.
          

          希望这会有所帮助。

          【讨论】:

          • 'io.sockets.emit' 与 'io.emit' 相同,而不是 'socket.emit'
          • 'socket.to('game').emit' 等于 'socket.broadcast.to('game').emit' 所以上面的评论是错误的
          【解决方案6】:

          来自@LearnRPG 的答案,但使用的是 1.0:

           // send to current request socket client
           socket.emit('message', "this is a test");
          
           // sending to all clients, include sender
           io.sockets.emit('message', "this is a test"); //still works
           //or
           io.emit('message', 'this is a test');
          
           // sending to all clients except sender
           socket.broadcast.emit('message', "this is a test");
          
           // sending to all clients in 'game' room(channel) except sender
           socket.broadcast.to('game').emit('message', 'nice game');
          
           // sending to all clients in 'game' room(channel), include sender
           // docs says "simply use to or in when broadcasting or emitting"
           io.in('game').emit('message', 'cool game');
          
           // sending to individual socketid, socketid is like a room
           socket.broadcast.to(socketid).emit('message', 'for your eyes only');
          

          回答@Crashalot评论,socketid来自:

          var io = require('socket.io')(server);
          io.on('connection', function(socket) { console.log(socket.id); })
          

          【讨论】:

          • 太棒了!您如何获得 socketid 以发送到单个套接字?
          • 编辑了您的问题的答案。基本上它是来自您的套接字对象的socket.id
          • 对于发送给个人,您可以使用 socket.emit back who send it or you can group the connected clients and do @Crashalot
          【解决方案7】:

          我正在使用命名空间和房间 - 我发现

          socket.broadcast.to('room1').emit('event', 'hi');
          

          在哪里工作

          namespace.broadcast.to('room1').emit('event', 'hi');
          

          没有

          (如果其他人也面临这个问题)

          【讨论】:

            【解决方案8】:

            这里是关于从 0.9.x 到 1.x 发生了什么变化的更完整的答案。

             // send to current request socket client
             socket.emit('message', "this is a test");// Hasn't changed
            
             // sending to all clients, include sender
             io.sockets.emit('message', "this is a test"); // Old way, still compatible
             io.emit('message', 'this is a test');// New way, works only in 1.x
            
             // sending to all clients except sender
             socket.broadcast.emit('message', "this is a test");// Hasn't changed
            
             // sending to all clients in 'game' room(channel) except sender
             socket.broadcast.to('game').emit('message', 'nice game');// Hasn't changed
            
             // sending to all clients in 'game' room(channel), include sender
             io.sockets.in('game').emit('message', 'cool game');// Old way, DOES NOT WORK ANYMORE
             io.in('game').emit('message', 'cool game');// New way
             io.to('game').emit('message', 'cool game');// New way, "in" or "to" are the exact same: "And then simply use to or in (they are the same) when broadcasting or emitting:" from http://socket.io/docs/rooms-and-namespaces/
            
             // sending to individual socketid, socketid is like a room
             io.sockets.socket(socketid).emit('message', 'for your eyes only');// Old way, DOES NOT WORK ANYMORE
             socket.broadcast.to(socketid).emit('message', 'for your eyes only');// New way
            

            我想编辑@soyuka 的帖子,但我的编辑被同行评审拒绝了。

            【讨论】:

              【解决方案9】:

              其他情况

              io.of('/chat').on('connection', function (socket) {
                  //sending to all clients in 'room' and you
                  io.of('/chat').in('room').emit('message', "data");
              };
              

              【讨论】:

                【解决方案10】:

                broadcast.emit 将 msg 发送给所有其他客户端(发送者除外)

                socket.on('cursor', function(data) {
                  socket.broadcast.emit('msg', data);
                });
                

                【讨论】:

                  【解决方案11】:

                  对于房间内的命名空间,循环房间中的客户列表(类似于 Nav 的回答)是我发现的仅有的两种可行的方法之一。另一种是使用排除。例如

                  socket.on('message',function(data) {
                      io.of( 'namespace' ).in( data.roomID ).except( socket.id ).emit('message',data);
                  }
                  

                  【讨论】:

                  • except 已从 1.x 中删除:/
                  【解决方案12】:

                  使用这个编码

                  io.sockets.on('connection', function (socket) {
                  
                      socket.on('mousemove', function (data) {
                  
                          socket.broadcast.emit('moving', data);
                      });
                  

                  这个 socket.broadcast.emit() 将在函数中发出任何东西,除了正在发出的服务器

                  【讨论】:

                  • 如果回调是在另一个文件中定义的,你如何在其中获得io
                  • 我的应用在多个文件中,我将它们与 PrePros 或 Koala 连接,而不是要求它们,它允许我共享它们的所有变量
                  • 或将io 设为全局
                  猜你喜欢
                  • 2016-06-02
                  • 1970-01-01
                  • 2017-08-11
                  • 1970-01-01
                  • 2014-07-29
                  • 2016-12-17
                  • 2013-09-14
                  相关资源
                  最近更新 更多