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');
});
}