Manage multiple tabs (but same user) in socket.io

后端 未结 4 949
天涯浪人
天涯浪人 2020-12-02 16:15

I\'m having some problems with socket.io, and I have no idea how to solve it. I\'ve an app with a login system with socket.io to manage user interactions. Also I\'ve an arra

4条回答
  •  时光取名叫无心
    2020-12-02 16:49

    It sounds like you may be referring to the socket id in your question, not the session id. If you have an express session you can use the session id, which will be the same regardless of how many tabs are open as long as they use the same browser and it's not in "private" mode. Take a look at this question for how to enable sessions in socket.io.

    socket.io and session?

    Update: When you're saving the session id, you'll associate it with the user's nickname and the connected sockets. Then you can iterate through each socket and send the message. Something like the following:

    [
        {sessionId: '12345', nickname: 'timmay!', socketIds: [1, 2, 3]},
        {sessionId: '23456', nickname: 'pete', socketIds: [4, 5, 6]}
    ]
    

    When another connection is established you push the new socket id into the socketIds array, and when a user disconnects you remove the id.

    Another option might be to only allow one tab per user per session. You can store a single socketId and when a new socket connects for the same user, you can disconnect the original socket and use the new one instead.

提交回复
热议问题