Commit c548a669 by amir

tool for emitting events

parent 7b313974
const express = require('express');
const http = require('http');
const url = require('url');
const WebSocket = require('ws');
const fs = require('fs');
const schedule = require('node-schedule');
var myArgs = require('optimist').argv,
help = './websocketExpress -p port -f file-path [-d delay-between-samples]';
/**
* some validation
*/
if ((myArgs.h)||(myArgs.help)) {
console.log(help);
process.exit(0);
}
if (myArgs.f == null){
console.log('please insert file path');
process.exit(0);
}
if (myArgs.d >0){
rule = new schedule.RecurrenceRule();
rule.second = myArgs.d;
rule.minute = 0;
}
console.log('myArgs: ', myArgs);
const app = express();
app.use(function (req, res) {
res.send({ msg: "hello" });
});
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
var index = 0;
var sendJson = function(){
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
var currentObj = jsonFile[index];
client.send(JSON.stringify(currentObj));
index = ++index % jsonFile.length;
}
});
}
fs.readFile(myArgs.f, (err, data) => {
if (err) throw err;
jsonFile = JSON.parse(data);
console.log('finished reading: ' + myArgs.f);
});
wss.on('connection', function connection(ws, req) {
//const location = url.parse(req.url, true);
// You might use location.query.access_token to authenticate or share sessions
// or req.headers.cookie (see http://stackoverflow.com/a/16395220/151312)
ws.on('message', function incoming(message) {
console.log('received: %s', message);
if (myArgs.d > 0){
var j = schedule.scheduleJob('*/' + myArgs.d + ' * * * * * *', sendJson);
} else {
client.send(JSON.stringify(jsonFile));
}
});
});
server.listen(myArgs.p, function listening() {
console.log('Listening on %d', server.address().port);
});
[
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"BMW", "models":[ "320", "X3", "X5" ] },
{ "name":"Fiat", "models":[ "500", "Panda" ] }
]
{
"name": "ws-event-emulator",
"version": "1.0.0",
"description": "emulate events in websocket",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"event",
"emit"
],
"author": "amir aharon <amir.aharon@ipgallery.com>",
"license": "ISC",
"dependencies": {
"express": "^4.16.2",
"fs": "0.0.1-security",
"http": "0.0.0",
"node-schedule": "^1.2.5",
"optimist": "^0.6.1",
"ws": "^3.2.0"
},
"bin": {
"ws-event-emulator": "./app.js"
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment