Optimization node.js



  • Hey, everybody, I've decided to study Node.js. Started training with sockets. I've faced this question: I'd like to know if I did the optimization algorithm, if you don't tell me what the mistakes are.

    var CurrentX;
    var EndX;
    

    data.on('connection', function(socket){
    socket.on('GetX', function (data) {

       CurrentX = 0;
       EndX = data;
    
    
       var interval = setInterval(function() {
           CurrentX++;
           socket.emit('message', Xpos);
           socket.broadcast.emit('message', Xpos);
       }, 50);
    
       if (CurrentX == EndX) {
       clearInterval(interval);
    }
    

    });



  • Potential challenges

    1. It's scary to see socket.on and setInterval Requisitions GetX from one client will start N intervals at 50ms. In addition to the pointless use of resources, the server will start to simulate messages 'message' in N more often. Use it. socket.once
    2. if(CurrentX == EndX) - an unsatisfactory client sends data=1 and your interval never stops. Try it. CurrentX >= EndX or inspection data corrective.
      The golden rule is "the man to trust the client"
    3. broadcast.emit sends the coordinates of the current WEM site to the compounds, including the current compound. There is a duplication of data that is being sent. https://ru.stackoverflow.com/questions/474114/%D0%9E%D0%BF%D1%82%D0%B8%D0%BC%D0%B8%D0%B7%D0%B0%D1%86%D0%B8%D1%8F-node-js/474422?noredirect=1#comment535890_474422

    General thoughts

    If you're writing something like a game, it's a little different to make an alert.

    1. On the server, keep a list of site coordinates on the current map.
    2. Separate events like moving customers change the information on this map.
    3. Newly connected client, sign for a valid card at a given interval. (Preventions before broadcast - We can send not one global map to all, but local maps relevant to the current client, suggesting changes outside them as non-material)
    4. When the client's shut down, clear the interval.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2