Setting up a socket.io room for a specific group based on url. Node.js, Express, Angluarjs

后端 未结 1 1519
故里飘歌
故里飘歌 2021-02-03 16:21

I have a web application running on node using express, angular, mongodb and socket.io where users belong to groups. In those groups I need to set up a chat socket whereby only

1条回答
  •  醉梦人生
    2021-02-03 16:47

    I'd recommend setting up namespaces for each room you have your chat in. I did something similar in my own code. Note: Rooms and namespaces are a little different from each other in socket.io itself (socket.io has both: http://socket.io/docs/rooms-and-namespaces/).

    In the Server code:

    I have a method under socket.on('connection') that is similar to

    socket.on('groupConnect', function(group){
        var groupNsp = io.of('/' + group);
    }
    

    This essentially makes sure that a namespace is exists under the name of the desired one. It doesn't mess it up or reset the namespace when it is called again.

    Then for receiving the messages:

    socket.on('message', function(data){
        var msg = data.msg;
        var nsp = data.nsp;
        io.of(nsp).emit('message', msg);
    }
    

    You could also add the nsp to the data you have already and then just send the data again to the clients.

    Then, in the client code:

    var socketOut = io.connect('http://yourdomain:1337/');
    var someGroupOrMethodToGetGroup;
    socketOut.emit('groupConnect', someGroupOrMethodToGetGroup);
    var nsp;
    setTimeout(function(){
        socket = io.connect('http://yourdomain:1377/' + someGroupOrMethodToGetGroup);
        socket.on('message', function(msg){
            displayMessage(msg);
        }
        nsp = '/' + someGroupOrMethodToGetGroup;
    }, 1500);
    

    Then in my displayMessage code I have:

    socketOut.emit('message', { msg: desiredMessage, nsp: nsp });
    

    0 讨论(0)
提交回复
热议问题