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

发布于 2024-12-03 18:36:41 字数 648 浏览 1 评论 0原文

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

服务器端 JavaScript:

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

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

客户端 JavaScript:

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

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

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:

Serverside 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:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

堇年纸鸢 2024-12-10 18:36:41

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

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

相反,您希望向所有 sockets

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

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

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

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);
幻想少年梦 2024-12-10 18:36:41

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

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

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

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

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.

这个俗人 2024-12-10 18:36:41

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

这就是我正在做的:

服务器端

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

客户端:< /强>

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

As of socket.io version 0.9, "emit" no longer worked for me, and I've been using "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]);
        }
});
空‖城人不在 2024-12-10 18:36:41

根据此广播
对于nodejs服务器,你可以使用这个:

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

一定要初始化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!');
});

在这种情况下,当用户到达你的服务器时,将会有“event_hello”广播到所有带有json对象的web-socket客户端 {message: 'Hello插座'}。

According to this Broadcasting.
With nodejs server, you can use this:

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

Be sure to initialise websocket, for example:

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'}.

四叶草在未来唯美盛开 2024-12-10 18:36:41

您可以按照此示例来实现您的场景。

您可以让所有客户端加入公共房间来发送一些更新。
每个套接字都可以像这样加入房间:

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

然后您可以让客户端在包含多个客户端数据(id 和状态)的套接字中输入密钥,如果一个客户端的状态发生变化,您可以像这样在套接字上接收更改事件:

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

现在您想要所有其他客户端要获得更新,因此您可以执行以下操作:

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

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

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.

甩你一脸翔 2024-12-10 18:36:41

这对我有用:

io.in("room1").emit(/* ... */)

正如 socket.io 发出备忘单中所述:https://socket.io/docs/v3/emit-cheatsheet/

This worked for me:

io.in("room1").emit(/* ... */)

As explained in the socket.io emit cheatsheet: https://socket.io/docs/v3/emit-cheatsheet/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文