Javascript 使用 Socket.io 更新所有客户端?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7352164/
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-08-24 01:56:15  来源:igfitidea点击:

Update all clients using Socket.io?

javascriptnode.jssocket.io

提问by Hyman

Is it possible to force all clients to update using socket.io? I've tried the following, but it doesn't seem to update other clients when a new client connects:

是否可以强制所有客户端使用 socket.io 进行更新?我尝试了以下操作,但是当新客户端连接时,它似乎没有更新其他客户端:

Serverside JavaScript:

服务器端 JavaScript:

I'm attempting to send a message to all clients, which contains the current number of connected users, it correctly sends the amount of users.... however the client itself doesn't seem to update until the page has been refreshed. I want this to happen is realtime.

我正在尝试向所有客户端发送一条消息,其中包含当前连接的用户数,它正确地发送了用户数量......但是客户端本身似乎在页面刷新之前不会更新。我希望这是实时发生的。

var clients = 0;
io.sockets.on('connection', function (socket) {
  ++clients;
  socket.emit('users_count', clients);    
  socket.on('disconnect', function () {
    --clients;
  });
});

Clientside JavaScript:

客户端 JavaScript:

var socket = io.connect('http://localhost');

socket.on('connect', function(){
  socket.on('users_count', function(data){
    $('#client_count').text(data);
    console.log("Connection");
  });
});

回答by Matt

It's not actually sending an update to the other clients at all, instead it's just emitting to the client that just connected (which is why you see the update when you first load)

它实际上根本没有向其他客户端发送更新,而只是向刚刚连接的客户端发送(这就是您在第一次加载时看到更新的原因)

// socket is the *current* socket of the client that just connected
socket.emit('users_count', clients); 

Instead, you want to emit to allsockets

相反,您想要发送到所有套接字

io.sockets.emit('users_count', clients);

Alternatively, you can use the broadcast function, which sends a message to everyone except the socket that starts it:

或者,您可以使用广播功能,该功能向除启动它的套接字之外的所有人发送消息:

socket.broadcast.emit('users_count', clients);

回答by houkanshan

I found that using socket.broadcast.emit()will only broadcast to the current "connection", but io.sockets.emitwill broadcast to all the clients. here the server is listening to "two connections", which are exactlly 2 socket namespaces

我发现使用socket.broadcast.emit()只会广播到当前的“连接”,但io.sockets.emit会广播到所有客户端。这里服务器正在侦听“两个连接”,它们恰好是 2 个套接字命名空间

io.of('/namespace').on('connection', function(){
    socket.broadcast.emit("hello");
});
io.of('/other namespace').on('connection',function(){/*...*/});

i have try to use io.sockets.emit()in one namespace but it was received by the client in the other namespace. however socket.broadcast.emit()will just broadcast the current socket namespace.

我尝试在一个命名空间中使用io.sockets.emit()但它被另一个命名空间中的客户端接收。然而socket.broadcast.emit()只会广播当前的套接字命名空间。

回答by Katie

As of socket.io version 0.9, "emit" no longer worked for me, and I've been using "send"

从 socket.io 0.9 版开始,“emit”不再对我有用,我一直在使用“send”

Here's what I'm doing:

这是我在做什么:

Server Side:

服务器端

var num_of_clients = io.sockets.clients().length;
io.sockets.send(num_of_clients);

Client Side:

客户端:

ws = io.connect...
ws.on('message', function(data)
{
var sampleAttributes = fullData.split(',');
if (sampleAttributes[0]=="NumberOfClients")
        {
            console.log("number of connected clients = "+sampleAttributes[1]);
        }
});

回答by Rdavial

You can follow this example for implementing your scenario.

You can let all of clients to join a common room for sending some updates.
Every socket can join room like this: 

currentSocket.join("client-presence") //can be any name for room

Then you can have clients key in you sockets which contains multiple client's data(id and status) and if one client's status changes you can receive change event on socket like this:

socket.on('STATUS_CHANGE',emitClientsPresence(io,namespace,currentSocket); //event name should be same on client & server side for catching and emiting

and now you want all other clients to get updated, so you can do something like this:

emitClientsPresence => (io,namespace,currentSocket) {
  io.of(namespace)
        .to(client-presence)
        .emit('STATUS_CHANGE', { id: "client 1", status: "changed status" });
}

This will emit STATUS_CHANGE event to all sockets that have joined "client-presence" room and then you can catch same event on client side and update other client's status.