forked from koding/koding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream_socketio.js
More file actions
executable file
·112 lines (95 loc) · 3.31 KB
/
Copy pathstream_socketio.js
File metadata and controls
executable file
·112 lines (95 loc) · 3.31 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
var EventEmitter = require('events').EventEmitter;
var Stream = require('stream').Stream;
var io = require('socket.io');
var fs = require('fs');
var bundle = (function () {
var cache = null;
var file = __dirname + '/../browser/bundle.js';
return function (req, res) {
if (cache) {
var headers = {
'content-type' : 'text/javascript',
'last-modified' : cache.modified.toGMTString(),
'date' : new Date().toGMTString(),
};
var ims = req.headers['if-modified-since'];
if (ims) {
var m = new Date(ims);
if (m >= cache.modified) {
res.writeHead(304, headers);
res.end();
return;
}
}
res.writeHead(200, headers);
res.end(cache.source);
}
else fs.stat(file, function (err0, stat) {
fs.readFile(file, function (err1, src) {
if (err0 || err1) {
var e = err0 || err1;
console.error(e.message || e);
res.writeHead(500, { 'content-type' : 'text/plain' });
res.end('an error occurred loading the bundle');
}
else {
cache = {
source : src,
modified : stat.mtime,
};
bundle(req, res);
}
});
});
};
})();
module.exports = function (webserver, mount, ioOptions) {
if (ioOptions['log level'] === undefined) {
ioOptions['log level'] = -1;
}
var sock = io.listen(webserver, ioOptions);
sock.set('logger', {
error : function () {},
warn : function () {},
info : function () {},
debug : function () {}
});
var server = new EventEmitter;
server.socket = sock;
if (mount && webserver.use) {
webserver.use(function (req, res, next) {
if (req.url.split('?')[0] === mount) {
bundle(req, res);
}
else next()
});
}
else if (mount) {
if (!webserver._events) webserver._events = {};
var ev = webserver._events;
if (!ev.request) ev.request = [];
if (!Array.isArray(ev.request)) ev.request = [ ev.request ];
ev.request.push(function (req, res) {
if (!res.finished && req.url.split('?')[0] === mount) {
bundle(req, res);
}
});
}
sock.sockets.on('connection', function (client) {
var stream = new Stream;
stream.socketio = client;
stream.readable = true;
stream.writable = true;
stream.write = client.send.bind(client);
stream.end = stream.destroy = client.disconnect.bind(client);
client.on('message', stream.emit.bind(stream, 'data'));
client.on('error', stream.emit.bind(stream, 'error'));
client.on('disconnect', function () {
stream.writable = false;
stream.readable = false;
stream.emit('end');
});
server.emit('connection', stream);
});
return server;
};