Search code examples
javascriptnode.jsserver-sent-eventssocket.io

Nodejs - socketio - update info in all browser windows


I just started up learning how to make web applications. I am making a webserver in nodejs (a to-do list app). I am using the express framework, and mongodb as database. For communication between the client and the server i am using socket.io.

I can't find a way to make it so that when the server emits and event the client will update the info on all of his open windows of the page. Right now the info updates only on the window that triggered the event on ther server. This is the server code:

Server code:

var io = require('socket.io').listen(server);
io.of('/home').on('connection', function (socket) { 
    socket.on('newListGroup', function (data) {
        ...
        socket.emit('groupNo', obj);
    });
}); `

Client javascript:

var socket = io.connect('http://localhost/login');
socke.on('groupNo', function(data){ ... });
$('#newListGroup').blur(function() {
    socketLogin.emit('newListGroup', {newGroup:newGroup});
});

Can this work or should I take another approach?


Solution

  • You can broadcast a message to all sockets like this:

    var io = require('socket.io').listen(server);
    io.of('/home').on('connection', function (socket) {
        socket.on('newListGroup', function (data) {
        socket.broadcast.emit('groupNo', obj); });
    });
    

    It should be limited to the namespace but you will probably have to implement your own logic for broadcasting only to windows on the same client (probably using authentication) if that is what you want to do.