Merge pull request #163 from hybridgroup/replace-socket-io-with-server-sent-events

Replace Express.IO/Socket.IO with Express/SSEs
This commit is contained in:
Ron Evans 2014-04-09 10:20:31 -07:00
commit 93ec358f9b
2 changed files with 34 additions and 22 deletions

View File

@ -8,9 +8,10 @@
"use strict";
var fs = require('fs');
var fs = require('fs'),
https = require('https');
var express = require('express.io'),
var express = require('express'),
namespace = require('node-namespace');
namespace("Cylon", function() {
@ -36,7 +37,9 @@ namespace("Cylon", function() {
key: fs.readFileSync(opts.key || __dirname + "/ssl/server.key")
}
this.server = express().https(options).io();
this.server = express();
this.server.https = https.createServer(options, this.server);
this.server.set('title', 'Cylon API Server');
@ -66,7 +69,7 @@ namespace("Cylon", function() {
this.configureRoutes();
this.server.listen(this.port, this.host, function() {
this.server.https.listen(this.port, this.host, null, function() {
var title = self.server.get('title');
Logger.info(title + " is listening on " + self.host + ":" + self.port);
});
@ -142,6 +145,32 @@ namespace("Cylon", function() {
});
});
this.server.get("/robots/:robotname/devices/:devicename/events/:eventname", function(req, res) {
var robotname = req.params.robotname,
devicename = req.params.devicename,
eventname = req.params.eventname;
master.findRobotDevice(robotname, devicename, function(err, device) {
if (err) { res.json(err); }
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Connection': 'keep-alive',
'Cache-Control': 'no-cache'
});
var writeData = function(data) {
res.write("data: " + JSON.stringify(data) + "\n\n")
};
device.on(eventname, writeData);
res.on('close', function() {
device.removeListener(eventname, writeData);
});
});
});
this.server.get("/robots/:robotname/devices/:devicename/commands", function(req, res) {
var robotname = req.params.robotname,
devicename = req.params.devicename;
@ -180,23 +209,6 @@ namespace("Cylon", function() {
res.json(err ? err : connection.data());
});
});
this.server.get("/robots/:robotname/devices/:devicename/events", function(req, res) {
req.io.route('events');
});
this.server.io.route('events', function(req) {
var robotname = req.params.robotname,
devicename = req.params.devicename
master.findRobotDevice(robotname, devicename, function(err, device) {
if (err) { return req.io.respond(err); }
device.on('update', function(data) {
req.io.emit('update', { data: data });
});
});
});
};
return ApiServer;

View File

@ -39,7 +39,7 @@
"dependencies": {
"async": "~0.2.9",
"node-namespace": "~1.0.0",
"express.io": "~1.1.13",
"express": "~3.5.1",
"robeaux": ">= 0.0.4"
}
}