-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
65 lines (57 loc) · 1.64 KB
/
app.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
65
var ShareDB = require('sharedb');
var browserChannel = require('browserchannel').server
var Duplex = require("stream").Duplex
var serveStatic = require('serve-static')
var connect = require("connect");
var richText = require('rich-text')
ShareDB.types.register(richText.type)
var server = connect()
server.use(serveStatic(__dirname + "/public", {'index': ['quill.html']}));
var db = require('mongodb').connect('mongodb://localhost:27017', function(err, mongo) {
if (err) throw err;
var db = require('sharedb-mongo')({mongo: mongo});
});
var backend = ShareDB({db: db});
var numClients = 0
server.use(browserChannel({
cors: "*",
sessionTimeoutInterval: 5000
}, function(client) {
var stream;
numClients++;
stream = new Duplex({
objectMode: true
});
stream._write = function(chunk, encoding, callback) {
console.log('s->c ', JSON.stringify(chunk));
if (client.state !== 'closed') {
client.send(chunk);
}
return callback();
};
stream._read = function() {};
stream.headers = client.headers;
stream.remoteAddress = stream.address;
client.on('message', function(data) {
console.log('c->s ', JSON.stringify(data));
return stream.push(data);
});
stream.on('error', function(msg) {
console.log('error')
return client.stop();
});
client.on('close', function(reason) {
stream.push(null);
stream.emit('close');
numClients--;
return console.log('client went away', numClients);
});
stream.on('end', function() {
return client.close();
});
return backend.listen(stream);
}));
var port = 8080;
server.listen(port, function() {
return console.log("Listening on " + port);
});