简体   繁体   English

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

[英]Update all clients using Socket.io?

Is it possible to force all clients to update using socket.io?是否可以强制所有客户端使用 socket.io 进行更新? I've tried the following, but it doesn't seem to update other clients when a new client connects:我尝试了以下操作,但是当新客户端连接时,它似乎没有更新其他客户端:

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");
  });
});

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 all sockets相反,您想要发送到所有套接字

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);

I found that using socket.broadcast.emit() will only broadcast to the current "connection", but io.sockets.emit will broadcast to all the clients.我发现使用socket.broadcast.emit()只会广播到当前的“连接”,但io.sockets.emit会广播到所有客户端。 here the server is listening to "two connections", which are exactlly 2 socket namespaces这里服务器正在侦听“两个连接”,它们恰好是 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.我尝试在一个命名空间中使用io.sockets.emit()但它被另一个命名空间中的客户端接收。 however socket.broadcast.emit() will just broadcast the current socket namespace.然而socket.broadcast.emit()只会广播当前的套接字命名空间。

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]);
        }
});

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:然后你可以让客户端在你的套接字中包含多个客户端的数据(id 和状态),如果一个客户端的状态发生变化,你可以在套接字上接收更改事件,如下所示:

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.这将向所有加入“客户端存在”房间的套接字发出 STATUS_CHANGE 事件,然后您可以在客户端捕获相同的事件并更新其他客户端的状态。

According to this Broadcasting .根据这个广播 With nodejs server, you can use this:使用 nodejs 服务器,你可以使用这个:

io.emit('event_id', {your_property: 'your_property_field'});

Be sure to initialise websocket, for example:一定要初始化websocket,例如:

var express = require('express');
var http = require('http');
var app = express();
var server = http.Server(app);
var io = require('socket.io')(server);

app.get('/', function (req, res) {
    res.send('Hello World!');
    io.emit('event_hello', {message: 'Hello Socket'});
});

server.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

In this case, when user reach your server, there will be "event_hello" broadcasted to all web-socket clients with a json object {message: 'Hello Socket'}.在这种情况下,当用户到达您的服务器时,将使用 json 对象 {message: 'Hello Socket'} 向所有 web-socket 客户端广播“event_hello”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM