Saturday, 20 August 2016

Node.js: creating bunch of websocket client connections to send a burst of messages?

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

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...