Teogenes Moura Teogenes Moura - 3 years ago 117
Javascript Question

emit to all sockets not working Socket.io

I'm trying to emit a message to all sockets connected to my server using socket.io. So far, the code is as follows:

if(electionExists) {
var connectedClients = io.sockets.adapter.rooms[electionRequested].sockets;
for(client in connectedClients) {
socket.to(client).emit("isVoteValid", {voteToValidate: voteToValidate});

I made sure that it enters the if(electionExists) condition. Also, I've printed out the array of connected clients, which looks like this:

{ SdiVoIUuGfFL5AJXAAAA: true, 'wLh-EfkAIrWpjx6nAAAC': true }

and just for the sake of it, I printed each client in the loop, which leads to this:


Therefore, I'm led to believe that the problem is not on getting the proper socket id's. However, the emit event doesn't work. On the client side I have this:

socket.on("isVoteValid", function(obj) {
console.log("it enters isVoteValid");

which is really, really simple but the console.log never happens. I really can't see why it is not working. Anyone got an idea?

Answer Source

If you wanted to broadcast your message then use following code

if(electionExists) {
      socket.broadcast.emit("isVoteValid", {voteToValidate: voteToValidate});

or you can also use this

if(electionExists) {
      io.sockets.emit("isVoteValid", {voteToValidate: voteToValidate});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download