-
Notifications
You must be signed in to change notification settings - Fork 89
/
serv.js
65 lines (54 loc) · 1.86 KB
/
serv.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
63
64
"use strict";
// Simple Swarm sync server: picks model classes from a directory,
// starts a WebSocket server at a port. Serves some static content,
// although I'd recomment to shield it with nginx.
var fs = require('fs');
var path = require('path');
var url = require('url');
var http = require('http');
var nopt = require('nopt');
var ws_lib = require('ws');
var pushserve = require('pushserve');
var Swarm = require('swarm');
var EinarosWSStream = Swarm.EinarosWSStream;
var options = nopt({
models : path,
index : path,
port : Number
});
// boot model classes
var modelPathList = options.models||'model/';
modelPathList.split(/[\:;,]/g).forEach(function (modelPath) {
modelPath = path.resolve(modelPath);
console.log('scanning',modelPath);
var modelClasses = fs.readdirSync(modelPath), modelFile;
while (modelFile = modelClasses.pop()) {
if (!/^\w+\.js$/.test(modelFile)) { continue; }
var modpath = path.join(modelPath, modelFile);
var fn = require(modpath);
if (fn.constructor !== Function) { continue; }
if (fn.extend !== Swarm.Syncable.extend) { continue; }
console.log('Model loaded', fn.prototype._type, ' at ', modpath);
}
});
// use file storage
var fileStorage = new Swarm.FileStorage('.swarm');
// create Swarm Host
var swarmHost = new Swarm.Host('swarm~nodejs', 0, fileStorage);
Swarm.localhost = swarmHost;
// start the HTTP server
var httpServer = pushserve(options);
console.log('HTTP server started');
// start WebSocket server
var wsServer = new ws_lib.Server({
server: httpServer
});
console.log('Swarm server started');
// add pipes
wsServer.on('connection', function(ws) {
var params = url.parse(ws.upgradeReq.url,true);
console.log('incomingWS %s', params.path);
// check the secret
// FIXME grant ssn
swarmHost.accept(new EinarosWSStream(ws), { delay: 50 });
});