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

后端 未结 4 951
天涯浪人
天涯浪人 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:57

    I know it has been a long time since you asked this, but Just 4 ago I published a module for node js, express and socket.io which manages that exactly thing you wanted. Check the Usage and Example, I hope you will find this module helpful!

    You can install it via NPM socket.io.users This is a node js module for socket.io applications. One user per client.

    Some of the usage code

    var express = require('express');
    var app = express();
    var server = require('http').createServer(app);
    var socketUsers = require('socket.io.users');
    //....
    socketUsers.Session(app);//IMPORTANT 
    //...
    var rootIo = require('socket.io')(server); //default '/' as namespace. 
    var chatIo = rootIo.of('/chat');
    
    var rootUsers = socketUsers.Users; /* default '/' as namespace.
    Each namespace       has IT's OWN users object list,
    but the Id of a user of any other namespace may 
    has the same value if       request comes from the same client-machine-user.
    This makes   easy to keep a kind of 
    synchronization between all users of all   different namespaces. */
    
    var chatUsers = socketUsers.Users.of('/chat'); //  
    
    
    rootIo.use(socketUsers.Middleware());/*IMPORTANT but no errors if you want
    to  skip it for a io.of(namespace) 
    that you don't want the socket.io.users' support.  */
    
    chatUsers.use(socketUsers.Middleware());
    
    chatUsers.on('connected',function(user){
    console.log(user.id + ' has connected to the CHAT');
    user.store.username = 'username setted by server side'; /*at the store
    property you can store any type of properties
    and objects you want to share between your user's sockets.  */
    user.socket.on('any event', function(data){ 
    /*user.socket is the current socket, to get all connected sockets from this  
    user, use: user.sockets */
    
    });
    chatIo.emit('set username',user.store.username);
    });
    
    rootUsers.on('connected',function(user){
       console.log('User has connected with ID: '+ user.id);
    });
    
    
    
    rootUsers.on('connection',function(user){
       console.log('Socket ID: '+user.socket.id+' is user with ID: '+user.id);
    });
    
    rootUsers.on('disconnected',function(user){
        console.log('User with ID: '+user.id+'is gone away :(');
    });
    
    //...server.listen blabla..
    

提交回复
热议问题