【问题标题】:How to get a list of connected socket objects (not socket IDs) in socket.io v1+?如何在 socket.io v1+ 中获取连接的套接字对象(不是套接字 ID)的列表?
【发布时间】:2016-05-13 03:09:55
【问题描述】:

我正在使用较新版本的 socket.io,但我不知道如何获取套接字对象的列表。我遵循了一些教程和 StackOverflow 答案,例如这个:

How to get all the sockets connected to Socket.io

我也查看了文档,但没有太大帮助。我找到的所有帖子都解释了如何获取 socketIds,但我需要套接字本身,这样我就可以只向某些套接字发射。

那么你如何获得实际的套接字本身,或者这在新版本的 Socket 中不再可能?

【问题讨论】:

    标签: socket.io


    【解决方案1】:

    您可以有几个选择:

    // An object with socket.id as property and socket object as value
    // You could iterate this with for/in or use `Object.keys()` to get the ids
    //   and then access each socket by id
    // io.sockets.connected
    
    var ids = Object.keys(io.sockets.connected);
    ids.forEach(function(id) {
        var socket = io.sockets.connected[id];
        // do something with socket here
    
    });
    
    // an array of sockets which you can iterate directly as an array.
    // io.sockets.sockets
    
    io.sockets.sockets.forEach(function(socket) {
        // do something with socket here
    
    });
    

    您也可以单独访问命名空间:

    // array of sockets in this namespace
    io.nsps['/'].sockets
    
    //  map of socket ids in this namespace
    io.nsps['/'].connected
    

    【讨论】:

      猜你喜欢
      • 2015-08-05
      • 2011-09-27
      • 2014-10-18
      • 2016-12-13
      • 2020-11-11
      • 1970-01-01
      • 2015-07-06
      • 2016-05-20
      • 1970-01-01
      相关资源
      最近更新 更多