forked from share/sharedb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
39 lines (34 loc) · 1.07 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
var http = require('http');
var express = require('express');
var ShareDB = require('sharedb');
var WebSocket = require('ws');
var WebSocketJSONStream = require('websocket-json-stream');
var backend = new ShareDB();
createDoc(startServer);
// Create initial document then fire callback
function createDoc(callback) {
var connection = backend.connect();
var doc = connection.get('examples', 'counter');
doc.fetch(function(err) {
if (err) throw err;
if (doc.type === null) {
doc.create({numClicks: 0}, callback);
return;
}
callback();
});
}
function startServer() {
// Create a web server to serve files and listen to WebSocket connections
var app = express();
app.use(express.static('static'));
var server = http.createServer(app);
// Connect any incoming WebSocket connection to ShareDB
var wss = new WebSocket.Server({server: server});
wss.on('connection', function(ws, req) {
var stream = new WebSocketJSONStream(ws);
backend.listen(stream);
});
server.listen(8080);
console.log('Listening on http://localhost:8080');
}