我想做的是从gpx文件中获取一个错误列表,然后将其发送到webSocket服务器,但是它们之间希望稍稍延迟1-3秒
const WebSocket = require('ws');
fs = require('fs');
var parser = require('xml2json');
const ws = new WebSocket('ws://172.18.0.4:3000');
coordinates = new Array();
//counter = 1;
if(!process.argv[2]){
console.error("Please add file from gpx directory eg. 'node index gsx.file'");
process.exit(1);
}
ws.on('open', function open() {
fs.readFile('./gpx/'+process.argv[2], function(err, data) {
var json = parser.toJson(data);
obj = JSON.parse(json);
coordinates = obj.gpx.trk.trkseg.trkpt;
ws.send(JSON.stringify(coordinates[0]), function ack(error) {
if(error){
console.log(error.message);
}
});
});
});
counter = 0;
ws.on('message', function incoming(data) {
let randomtime = randomInt(1000,3000)
if(counter < (coordinates.length -1)){
setTimeout(function() {
ws.send(JSON.stringify(coordinates[counter]), function ack(error) {
if(error){
console.log(error.message);
}
});
}, randomtime);
counter = counter + 1;
}else{
counter = 0;
}
});
ws.on('error', function error(err){
console.log(err);
});
function randomInt(low, high) {
return Math.floor(Math.random() * (high - low) + low)
}
问题是,当我运行此脚本时,它起步缓慢,随着我们做更多的事情而变得越来越快,我不确定为什么