E
E
Eugene2020-07-31 13:15:19
Node.js
Eugene, 2020-07-31 13:15:19

Handling users in nodejs server?

Good afternoon!
I ask for help in understanding the design of a client-server application.

Server on nodejs, socket IO, MongoDB database is used to connect with the client.

I need to authorize the user, then get the data from the database by ID and then process it on the server.

User data is processed and changed once per second.
for example

var io = require('socket.io').listen(server);
var timer;
io.on('connection', function (socket) {
    console.log('подключился пользователь');
    socket.on('disconnect', function () {
        console.log('пользователь отключился');
    });
    socket.on('initGame', (id) => { player.GetPlayerData(id,socket);});
});
// работа с данными пользователя

function UpdatePlayerData(data){
  setInterval(() => { 
   //обновление данных 
  }, 1000);
}
//получение данных с БД
function GetPlayerData(id, socket) {
    Player.findOne({ id: id}, function (err, res) {
        if (err) throw err;
             UpdatePlayerData(data);
        });  
}

I understand how it would work with one user, but here's how to work with more than one.

My assumptions:

when connecting, add a socket and data for processing to an array and once a second iterate through this array, changing the data.
in the same way and send data to the client.

I can't figure out in my head what it should look like.

And confuses setInterval(func(),time) , which does not guarantee repetition within the set time. How else can the data be processed?

Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Shumov, 2020-07-31
@Genya24

The only downside is the timer. It is worth mastering the full event interaction and carrying out all operations in this way. For example, there is a GraphQL protocol and it has a Subscription that works just on a websocket. Other operations in the GraphQL server generate events and they are sent to everyone who subscribes to them.
In a more complex case, only the storage of the user-connection mapping is added and new data is sent to all user connections in a cycle

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question