R
R
Roman Korolyov2019-01-29 23:05:46
Node.js
Roman Korolyov, 2019-01-29 23:05:46

Why are sockets loaded ( Socket IO ) in node js?

Hi friends, I'm facing the same problem.
I made a socket connection in node js along with a request to the database, but the bottom line is that the socket sends a request to the user only after 10-20 seconds. That is, these requests, which are presented below, apparently take a long time to complete and after that they are sent to the socket.
Can you tell me if requests and sending are implemented correctly and why they take so long to send to clients
(I have been learning node not so long ago, so I need good advice)

io.sockets.on('connection', function(socket){
      
      console.log('connect');

    setInterval(function() {
    connection.query('SELECT * FROM drops ORDER BY id DESC LIMIT 10', function(error, result, fields){
  socket.emit('games', result); 
  });	
    }, 2000);


    setInterval(function() {
    connection.query('SELECT COUNT(*) FROM users', function(error, result, fields){
  socket.emit('users', result['0']['COUNT(*)']); 
  });	

  connection.query('SELECT SUM(amount) FROM drops', function(error, result, fields){
  socket.emit('drops', result['0']['SUM(amount)']); 
  });	

    }, 3000);


});

Maybe you need some stubs on the client side?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
de1m, 2019-01-29
@de1m

In my opinion, such things immediately without processing are somehow not very correct to send immediately.
And about the topic, you first look at where the delay occurs.
Try this, it will be clear where the problem is:

setInterval(function () {
        let startTime = process.hrtime.bigint();
        connection.query('SELECT * FROM drops ORDER BY id DESC LIMIT 10', function (error, result, fields) {
            socket.emit('games', result);
        });
        let endTime = process.hrtime.bigint();
        console.log("DB Req1: " + (endTime - startTime)); // in nanosec.
    }, 2000);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question