How to save usernames from php session to socket.io library in nodejs and socket connection is disconnected when the page is refreshed. Why?

I am making a chat application for my web portal. I used to save username from php session in nodejs socket io library. I am confused .. is it ok to store 10k users in a socket object.if yes, then how to save a list of users? Another problem is that the user goes from one page to another. Disconnecting the connector and connecting again ... Does it affect the performance of my application or nodejs server?

I ask you to advise through textbooks or a blog. I have not yet found the relevant documents about connecting to the socket. Thanks in advance!

+4
source share
1 answer

You can save your data in socket. For instance,

On the server side, use for example

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

The socket connection is disconnected when the page is refreshed. Why?

This is the default behavior socket.io.

+3
source

Source: https://habr.com/ru/post/1663951/


All Articles