使用 Socket.io 更新所有客户端? [英] Update all clients using Socket.io?

查看:24
本文介绍了使用 Socket.io 更新所有客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

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

客户端 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);

这篇关于使用 Socket.io 更新所有客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆