This repository has been archived by the owner on Sep 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
59 lines (49 loc) · 1.69 KB
/
index.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
var fs = require('fs'),
path = require('path'),
clientScript,
socketHandlers = [];
function findSocketHandlers(mesh, targetPath, callback) {
// find files in the directory
fs.readdir(targetPath, function(err, files) {
(files || []).forEach(function(file) {
if (path.extname(file) == '.js') {
callback(path.basename(file, '.js'), require(path.join(targetPath, file)));
} // if
});
});
} // findSocketHandlers
function provideSocketScript(req, res, next) {
res.contentType('assets/sockets.js');
if (clientScript) {
res.send(clientScript);
}
else {
fs.readFile(path.resolve(__dirname, 'assets/sockets.js'), 'utf8', function(err, data) {
if (! err) {
clientScript = data;
res.send(clientScript);
} // if
});
} // if..else
}
exports.install = function(mesh, instance) {
var app = this;
// find socket handlers
findSocketHandlers(mesh, path.join(this.basePath, 'lib/sockets'), function(name, handler) {
socketHandlers.push(handler);
});
mesh.on('socket', function(socket) {
console.log('socket connected, attaching handlers: ', socketHandlers);
socketHandlers.forEach(function(handler) {
handler.call(handler, app, mesh, socket);
});
});
instance.get('/sockets.js', provideSocketScript);
};
exports.installGlobal = function(mesh, instance) {
mesh.socketio = require('socket.io').listen(instance);
mesh.socketio.sockets.on('connection', function(socket) {
console.log('socket connected');
mesh.emit('socket', socket);
});
};