node.js 使用 socket.io 创建已连接客户端列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8284116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:48:51  来源:igfitidea点击:

Create a list of Connected Clients using socket.io

node.jssocket.io

提问by Nyxynyx

Here are 2 related questions. Posting them together makes more sense.

这是2个相关的问题。将它们放在一起更有意义。

Question 1

问题 1

I have a node.js app which emits an event out to all clients, and all current clients will respond with a readyemit. How can I create a list of all the clients that replied to the initial emit, and what kind of identification can be used to distinguish the clients?

我有一个 node.js 应用程序,它向所有客户端发出一个事件,所有当前客户端都将响应一个ready发出。如何创建所有回复初始发出的客户端的列表,以及可以使用什么样的标识来区分客户端?

Question2:

问题2:

What I am trying to do after collect a list of connected clients, is to then access a MySQL database table of Nnumber of rows and assign each client Xrows each. These rows will be emitted back to their respective clients. How can this be done?

在收集连接的客户端列表后,我想要做的是访问一个N包含行数的MySQL 数据库表并为每个客户端分配每个X行。这些行将被发送回各自的客户端。如何才能做到这一点?

Current Code for Qn 1

Qn 1 的当前代码

Node Code

节点代码

setInterval(function() {
    util.log('Checking for new jobs...');
    dbCheckQueue(function(results) {  // checks if there are new rows to "distribute" to clients
        if (results.length) {
            util.log(results.length + ' new jobs found.');
            io.sockets.emit('job_available');
        }
    });
}, 10*1000);

Client-side JS Code

客户端JS代码

socket.on('job_available', function() {
                console.log('Job Available.. Responding with Ready!');
                socket.emit('ready');
            });

io.sockets.on('connection', function(socket) {
    socket.on('ready', function() {
        // UPDATE N rows with client_id in column checkout.
        // Then SELECTS * from table where checkout = client_id
        getListings(client_id, function(listings) {
            socket.emit('job', listings);   // send jobs
        });
    });
});

Current Code for Qn 2The code works for a single client, but how do I loop through all connected clients and perform the same updating of column and selecting of rows?

Qn 2当前代码该代码适用于单个客户端,但如何遍历所有连接的客户端并执行相同的列更新和行选择?

io.sockets.on('connection', function(socket) {
    socket.on('ready', function() {
        // UPDATE N rows with client_id in column checkout.
        // Then SELECTS * from table where checkout = client_id
        getListings(client_id, function(listings) {
            socket.emit('job', listings);   // send jobs
        });
    });
});

回答by 3rdEden

Socket.io provides you with a public api for that, so instead of hacking something up like Bryan suggest you can use:

Socket.io 为此提供了一个公共 api,所以不要像 Bryan 建议的那样破解一些东西,你可以使用:

io.sockets.clients()

That will returns an array of all connected clients.

这将返回所有已连接客户端的数组。

If you want all clients connected to a certain namespace:

如果您希望所有客户端都连接到某个命名空间:

io.of('/namespace').clients()

But you can even filter it even more.. if you want to have all sockets in a room:

但是您甚至可以对其进行更多过滤.. 如果您想在一个房间内拥有所有插座:

io.sockets.clients('room name here as first argument')

Will return a array of connected sockets for the room room name here as first argument

将返回房间的连接套接字数组 room name here as first argument

回答by rossipedia

You will need to keep track of the connected clients yourself. The simple way to do that would be to use an array:

您需要自己跟踪连接的客户端。这样做的简单方法是使用数组:

var clients = [];

io.sockets.on('connect', function(client) {
    clients.push(client); 

    client.on('disconnect', function() {
        clients.splice(clients.indexOf(client), 1);
    });
});

Then you can references that clientsarray on the server wherever you need to, in your readyevent handler or whatever. Something like:

然后你可以clients在你需要的任何地方,在你的ready事件处理程序或其他任何地方引用服务器上的该数组。就像是:

io.sockets.on('connection', function(socket) {
    socket.on('ready', function() {
        // UPDATE N rows with client_id in column checkout.
        // Then SELECTS * from table where checkout = client_id
        clients.forEach(function(client, index) {
            var client_id = index; // Just use the index in the clients array for now
            getListings(client_id, function(listings) {
                socket.emit('job', listings);   // send jobs
            });
        });
    });
});