简体   繁体   中英

How to store usernames from php session to socket.io library in nodejs and socket connection disconnects on page refresh.Why?

I am making a chat application for my web job portal.I used to save user's name from php session to nodejs socket io library..I am confused..it is ok to store 10k users in socket object.if yes then how to maintain that users list? Another problem is when user navigates from one page to another..socket disconnect and again connect..Does it effect my application performance or nodejs server perform?

Please guide me through tutorials or blog..I have not find relevant docs yet about socket connection management ..Thanks in advance!!

You can store your data into socket . For example,

On Server side, use like this,

    var socketIo = require('/socket.io').listen(8080);
    var usernames=[];    

    socketIo.sockets.on('connection', function (socket) {    
        socket.on('storeUserData', function (data) {  
           var userInfo = new Object();
           userInfo.userName = data.userName;
           userInfo.SocketId = socket.id;
            usernames.push(userInfo);
        });    

        socket.on('disconnect', function (data) {
         var len = usernames.length;

            for(var i=0; i<len; i++){
                var user = usernames[i];

                if(user.socketId == socket.id){
                    usernames.splice(i,1);
                    break;
                }
            }    
        });
    });

and on client side, you need to add this

<script>
    var userName = <?php echo $_SESSION['userName'] ?>;        
    var socket = io.connect('http://localhost', {port: 8080});    
    socket.on('connect', function (data) {
        socket.emit('storeUserData', { 'userName' : userName });
    });
</script>

Socket connection disconnects on page refresh.Why?

It is default behaviour of socket.io .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM