This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.js
51 lines (43 loc) · 1.48 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
40
41
42
43
44
45
46
47
48
49
50
51
const Automerge = require('automerge')
const Connection = require('./connection')
const net = require('net')
const HOST = '0.0.0.0'
const PORT = 9876
// Initialise an example document
const docSet = new Automerge.DocSet()
const initDoc = Automerge.change(Automerge.init(), doc => doc.hello = 'Hi!')
docSet.setDoc('example', initDoc)
// Print out the document whenever it changes
docSet.registerHandler((docId, doc) => {
console.log(`[${docId}] ${JSON.stringify(doc)}`)
})
// Make a change to the document every 3 seconds
setInterval(() => {
let doc = docSet.getDoc('example')
doc = Automerge.change(doc, doc => {
doc.serverNum = (doc.serverNum || 0) + 1
})
docSet.setDoc('example', doc)
}, 3000)
// This function is called every time a client connects to the server socket
function handler(socket) {
console.log(`[${socket.remoteAddress}:${socket.remotePort}] connected`)
const connection = new Connection(docSet, socket)
// Receiving data from the client
socket.on('data', (data) => {
if (!(data instanceof Buffer)) {
data = Buffer.from(data, 'utf8')
}
connection.receiveData(data)
})
socket.on('close', (data) => {
console.log(`[${socket.remoteAddress}:${socket.remotePort}] connection closed`)
connection.close()
})
socket.on('error', (err) => {
console.log(`[${socket.remoteAddress}:${socket.remotePort}] error: ${err}`)
})
}
// Listen on a TCP port
net.createServer(handler).listen(PORT, HOST)
console.log(`Listening on ${HOST}:${PORT}`)