user3092999 user3092999 - 27 days ago 23
Node.js Question

socket.broadcast.emit socket io

I tried the example chat application at socket.io, and that is worked fine. When I tried socket.broadcast.emit() function, it not worked.
Could anyone help me in that problem?
It is maybe a little bug, but I had waste an hour with it.

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket) {

socket.broadcast.emit('New participant connected.'); //DO NOT SEND ANY MESSAGE

socket.on('chat message', function(msg){

io.emit('chat message', msg);

});
});

http.listen(3000, function(){
console.log('listening on *:3000');
});

Answer

My guess would be that you're not listening to the "New participant connected." event in your clients.

Try this:

// server
socket.broadcast.emit('broadcast', 'New participant connected.');

// client
socket.on('broadcast', m => console.log('Received broadcast:', m));