0

I have a node websocket (require('ws')) server that i want to test in terms of load (active connections). Hence I am trying to write a node client app that makes several connections to the server and then more or less at the same time the client app will send some message through all connections. However i cant acoomplish that. Here is my source code:

 var WebSocket = require('ws');

   var connections = [];

   for(var i=0;i<10;i++)
   {        
       connections[i]=new WebSocket("ws://127.0.0.1:8080");

       connections[i].onopen = function()
       {      
           setTimeout(function() 
           {
                   connections[i].send(JSON.stringify({cmd:'pub',   data:'Hi!', channel:'TEMP'}));

           }, 5000);
       };

       connections[i].onmessage = function (evt) 
       { 
           var received_msg = evt.data;
               alert("Message is received...");
       };

       connections[i].onclose = function()
       { 
           alert("Connection is closed..."); 
       };
  }

When I execute this code:

connections[i].send(JSON.stringify({cmd:'pub', data:'Hi!', channel:'TEM ^ TypeError: Cannot call method 'send' of undefined

By the way, the setTimeout(function() is just an attempt to more or less synchronize the time to send the message burst.

Is this code ok? Please help on this

Mile

  • Your `i` variable is not correct inside the `setTimeout()` because the `for` loop has already finished by the time the `setTimeout()` fires. See the answers this was marked a dup of for solutions. – jfriend00 Mar 05 '16 at 01:02
  • Also see this answer: [What are good use cases for JavaScript self executing anonymous functions?](http://stackoverflow.com/questions/23124067/what-are-good-use-cases-for-javascript-self-executing-anonymous-functions/23124112#23124112) – jfriend00 Mar 05 '16 at 01:03
  • Oh, ok, the 'secret' here is to use the stack in order to remember each argument... I have put a just a function inside loop and the ws code inside the function, passing i by argument and now every i is processed inside function. But in this case if I want to call 5000 times (sockets) the stack must be enlarged right? – mileit97 mileit Mar 05 '16 at 10:20
  • Function arguments are not stored on a traditional stack in Javascript. This is because of closures and the ability for the arguments (or local variables) of a function to live longer than just the execution of the function itself. Thus, the arguments of a function (and their local variables) are garbage collected in Javascript, not stored on a stack. You should not need to make the stack larger in order to solve this problem as recommended with an internal function in the loop. – jfriend00 Mar 05 '16 at 17:38

0 Answers0