0
var WebSocket = require('ws')
var ws = [];

for (var i = 0; i < 10 ; ++i) {
    ws[i] = new WebSocket('ws://127.0.0.1:9898/echo/websocket');   

    ws[i].on('open', function() {
        ws[i].send('why');
    });

}

I am trying to open 10 websocket connections with nodejs, but somehow my loop doesnt work. What is wrong with my code? Thanks

laapsaap
  • 181
  • 11

2 Answers2

3

As Nitzan Shaked says your issue is due to the loop problem. When the callbacks start to fire all the i values are 9 here.

generic solution

As a generic solution, solve it using a simple closure.

var WebSocket = require('ws')
var ws = [];

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

    ws[i] = new WebSocket('ws://127.0.0.1:9898/echo/websocket');   
    ws[i].on('open', generator(ws[i]));

}

//generator makes a function with present object and returns it
var generator = function (k) {

    return function() {
        k.send('why');
    }

}

easy way

But the easiest way specific to your context would be by simply replacing ws[i] by a this

var WebSocket = require('ws')
var ws = [];

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

    ws[i] = new WebSocket('ws://127.0.0.1:9898/echo/websocket');   
    ws[i].on('open', function() {
         this.send('why');
    });

}
Community
  • 1
  • 1
Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101
  • Thank you, I am new to the node.js. I eventually solved the problem with closures and starting to understand how to "cope" with it ;) – laapsaap Oct 09 '13 at 16:01
0

Classic Javascript loop gotcha. Look here: Javascript infamous Loop issue?.

Basically at the point where the callback is called, ws[i].send(...), i refers to i at the end of the loop, not where you are defining the callback.

EDIT -- as Casey Chu noted, I have a silly bug in my code example. Instead of fixing it and coming up with a duplicate of other answers, I refer you to the (currently) 2 other answers which are perfectly working.

Community
  • 1
  • 1
Nitzan Shaked
  • 13,460
  • 5
  • 45
  • 54