how do I store socket resources from specific users with socket.io?

后端 未结 1 843
灰色年华
灰色年华 2020-12-30 17:47

I\'m designing a chat script which I test on my machine using different browsers. I\'m tryng to send messages to specific users with socket.io, so here it is :

         


        
相关标签:
1条回答
  • 2020-12-30 18:26

    The problem is that socket.id identifies sockets, not users, so if an user has several tabs opened at same time, every tab would have different socket.id, so if you store only one socket.id for an user, every time you assign it, you overwrite previous socketid.

    So, beside other possible problems, at least you need to do this or it won't work. I bet that you say about 1 socket for all browsers is that you overwrite the id every time (it happened to me when I started using Socket.IO)

    As a general rule, remember that you manage CONNECTIONS and not USERS... an user can have more than one connection!.

    On connection

    function onConnection( socket ) {
        var arr = users[incoming.phonenumber] || null;
        if( !arr ) 
            users[incoming.phonenumber] = arr = [];
        if( arr.indexOf( socket.id ) === -1 )
            arr.push( socket.id ); // Assigns socket id to user
    }
    

    On disconnection

    function onDisconnect( socket ) {
        var arr = users[incoming.phonenumber] || null;
        if( !arr ) return; // Should not happen since an user must connect before being disconnected
        var index = arr.indexOf( socket.id );
        if( index !== -1 )
            arr.splice( index, 1 ); // Removes socket id from user
    }
    
    0 讨论(0)
提交回复
热议问题