2

In script below I try to open ten websocket connections to server:

 var webscd=[];
 function initweb(){

   for (var c=0; c <10; c++){

      webscd[c]=new WebSocket(wsadress);

      webscd[c].onopen=function(evt){
        var binary = new Uint8Array(2);
        binary[0]=1;
        binary[1]=2;
        webscd[c].send(binary.buffer);                  
      };
      webscd[c].onclose=function(evt){};
      webscd[c].onmessage=function(evt){};
      webscd[c].onerror=function(evt){};
    }

} 
initweb();

But this script throws following error

'Uncaught TypeError: Cannot read property 'send' of undefined'

. What should i do?

maciekm
  • 257
  • 1
  • 5
  • 28
  • The only thing I can think of is that there's a problem with your `wsadress`. Did you spell "address" correctly when you declared the variable and then left out a "d" when you tried to use the variable? Or is the address simply invalid? – Jason Oct 02 '15 at 21:30
  • @Jason, wsaddres is ok. The problem is with `webscd[c].onopen=function(evt){.... webscd[c].send(binary.buffer); };` onopen function cant resolve `webscd[c].send(binary.buffer); ` properly. – maciekm Oct 02 '15 at 21:36
  • OK, I know what the problem is but I don't know how to fix it. It's this really frustrating thing with function closure. There might be something useful [here](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) but I can't figure out how to do it right. You can see the problem if you log `c` to the console inside your `onopen` function. The value is always equal to `10`, which is an invalid index for that array. They trick is to have your `onopen` function use the correct value for `c`. Hopefully someone will see this and show us how to do it. – Jason Oct 02 '15 at 22:57

1 Answers1

1

I figured out a way to do it without the closure stuff.

function create_ws() {
  var ws=new WebSocket("ws://127.0.0.1:1234");
  ws.onopen=function(evt){
    var binary = new Uint8Array(2);
    binary[0]=1;
    binary[1]=2;
    ws.send(binary.buffer);                  
  };
  ws.onclose=function(evt){};
  ws.onmessage=function(evt){};
  ws.onerror=function(evt){};
}

var webscd = [];

for(var i = 0; i < 10; i++) {
  webscd.push(create_ws());
}
Jason
  • 2,725
  • 2
  • 14
  • 22