Le Duy Khanh
Le Duy Khanh

Reputation: 1369

nodejs socket emit return undefined

I am trying to send to clients whenever a new connection issued.

My server side javascripts is :

var clients = 0;
io.sockets.on('connection', function (socket) {
clients ++;
console.log(clients);
socket.broadcast.emit('connect',socket.clients);
}

and my client side js to handle:

socket.on('connect', function (data) {
console.log('on'+data);});

the output is undefined (on undefined)

Where 's things wrong?

Upvotes: 0

Views: 963

Answers (1)

robertklep
robertklep

Reputation: 203554

socket.broadcast.emit('connect',socket.clients);
                                ^^^^^^^^^^^^^^ this should be 'clients'

Also, connect is a pre-defined event with socket.io, so you shouldn't reuse it or it might give unexpected results.

FWIW: socket.broadcast.emit will send a message to all connections except the current one. If that's not what you want (you want the message to be sent to all connections), use io.sockets.emit instead).

Upvotes: 3

Related Questions