Gourav Rathore
Gourav Rathore

Reputation: 41

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!!

Upvotes: 4

Views: 672

Answers (1)

Pritam
Pritam

Reputation: 695

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.

Upvotes: 3

Related Questions