-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
62 lines (52 loc) · 1.48 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
var ws = require("nodejs-websocket")
var Hapi = require('hapi');
var apiServer = new Hapi.Server();
var clientList = {};
function startWebSocket(port) {
var wsserver = ws.createServer(function(conn) {
conn.on("text", function(str) {
console.log('Client registered ' + str);
clientList[str] = conn;
})
conn.on("close", function(code, reason) {
for (var property in clientList) {
if (clientList.hasOwnProperty(property)) {
delete clientList[property];
}
}
console.log("Connection closed")
})
}).listen(port, console.log('WS server running on port: ' + port));
}
function startAPI(settings) {
apiServer.connection({
host: settings.httpHost,
port: settings.httpPort
});
apiServer.route({
method: 'GET',
path: '/hello',
handler: function (request, reply) {
reply('Hello!');
}
});
apiServer.route({
method: 'POST',
path: settings.apiPath,
handler: function(request, reply) {
var dId = request.headers.deviceauthuuid ? request.headers.deviceauthuuid : 'unknown';
console.log('Received POST data: device ' + dId);
if (clientList.hasOwnProperty(dId)) {
clientList[dId].sendText( JSON.stringify(request.payload) );
}
reply();
}
});
apiServer.start(function() {
console.log('APIServer running at:', apiServer.info.uri);
});
}
module.exports.listen = function(settings) {
startWebSocket( settings.wsPort );
startAPI( settings );
};