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
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.
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');
}
}
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');
});
}
Classic Javascript loop gotcha. Look here: Javascript infamous Loop problem?.
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.