Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
74
rated 0 times [  78] [ 4]  / answers: 1 / hits: 87941  / 13 Years ago, thu, september 8, 2011, 12:00:00

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

More From » node.js

 Answers
88

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

[#90199] Wednesday, September 7, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
domeniccolti

Total Points: 276
Total Questions: 98
Total Answers: 93

Location: India
Member since Fri, May 13, 2022
2 Years ago
domeniccolti questions
Mon, Oct 18, 21, 00:00, 3 Years ago
Thu, Oct 14, 21, 00:00, 3 Years ago
Thu, Jul 15, 21, 00:00, 3 Years ago
Sat, Oct 24, 20, 00:00, 4 Years ago
Thu, Sep 3, 20, 00:00, 4 Years ago
;