Joining socket io room on connect

后端 未结 3 1883
别跟我提以往
别跟我提以往 2021-02-05 04:55

I am trying to make a logged in user to join a certain socket.io room on connect. According to any examples I found on the net I seem to have emit some action from client to be

3条回答
  •  北恋
    北恋 (楼主)
    2021-02-05 05:22

    This is easily achieved. All you need to do is pass along a query parameter that the server understands.

    The following example isn't fully tested, but the idea will work. In this example, the roomname is determined from window.location.href on the client.

    Client

    // Last segment of path is roomName
    var roomName = window.location.href.substr(window.location.href.lastIndexOf('/') + 1);
    var socket = io({
        query: {
            roomName: roomName,
        },
    });
    

    Server

    var io = require('socket.io')(server);
    io.on('connection', function(socket) {
        var query = socket.handshake.query;
        var roomName = query.roomName;
        if(!roomName) {
            // Handle this as required
        }
        socket.join(roomName);
    });
    

提交回复
热议问题