Reputation: 38
Fair warning, I am a novice with javascript and ool. I am trying to put together a simple script to parse data out to a web socket. The script should be able to handle an infinite number of payloads.
This code works, although can only handle on payload at a time:
#!/usr/bin/env node
var io = require('socket.io-client');
var i=1
socket = io.connect('http://10.0.9.1:80');
var data = JSON.parse(process.argv[2]);
socket.on('connect', function(){
console.log('Emitting');
socket.emit('widget', data);
process.exit(0);
});
Wrapping the code in a loop with a logic test breaks it. No syntax errors, but it does not seem to call the emit method.
#!/usr/bin/env node
var io = require('socket.io-client');
var i=1
var data
while (true) {
i++
if ( process.argv[i] ) {
socket = io.connect('http://10.0.9.1:80');
data = JSON.parse(process.argv[2]);
socket.on('connect', function(){
console.log('Emitting');
socket.emit('widget', data);
});
} else {
process.exit(0);
};
};
Upvotes: 0
Views: 43
Reputation: 38
There were many mistakes in my first attempt. Clues from ControlAltDel and mrid made me realize my loop structure was all wrong. The loop should have been placed within the on('connect') like so:
#!/usr/bin/env node
var io = require('socket.io-client');
var i=1
var data
socket = io.connect('http://10.0.9.1:80');
socket.on('connect', function(){
while (true) {
i++;
if ( process.argv[i] ) {
data = JSON.parse(process.argv[i]);
console.log('Emitting ');
socket.emit('widget', data);
} else {
process.exit(0);
};
}
});
Upvotes: 0
Reputation: 35011
The sockets you are creating are async, so you end up creating a bunch of sockets and then call process.exit(0) before there's time to establish the connection
Upvotes: 1