LuisPinto LuisPinto - 5 months ago 7
Node.js Question

Why can't I use socket.emit.broadcast in this case?

Hello I have one counter on my server of how many people is connected. So whenever a user connects I want to send him the number of users. The problem is that when a users connect he sends the socket and the server recieve it. But when the server sends the socket with the number of users, client doesn't recieve this.

I'm having this problem when I use socket.broadcast.emit. If I use socket.emit I do recieve it.

Server.js

socket.on('update', function () {
console.log('Update', users)
socket.broadcast.emit('user',users) //Doesn't work
socket.emit('user', users) // Works
})


Index.js

$(document).ready(function() {

var users = 0
var socket = io()
.
.
.

socket.on('user', changeUsers)
socket.emit('update');
.
.
.

qk4 qk4
Answer

Broadcasting means sending a message to everyone else except for the socket that starts it.

So the connecting user will not get the broadcast.

from the socket.io docs

This may help clear things up to:

Sending and receiving events

Socket.IO allows you to emit and receive custom events. Besides connect, message and disconnect, you can emit custom events:

Server:

// note, io(<port>) will create a http server for you
var io = require('socket.io')(80);

io.on('connection', function (socket) {
  io.emit('this', { will: 'be received by everyone'});

  socket.on('private message', function (from, msg) {
    console.log('I received a private message by ', from, ' saying ', msg);
  });

  socket.on('disconnect', function () {
    io.emit('user disconnected');
  });
});
Comments