-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
49 lines (38 loc) · 1.27 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
module.exports = {
server: function (primus, options) {
primus.Spark.writable('latency', 0)
if (options.use_clock_offset) primus.Spark.writable('clock_offset', 0)
primus.transform('incoming', options.use_clock_offset ? setBoth : setLatency)
function setLatency(packet) {
var latency = packet.data._latency
if (latency && typeof latency == 'number') {
this.latency = latency
return false
}
}
function setBoth(packet) {
var latency = packet.data._latency
, client_clock = packet.data._clock
, cont = true
if (latency && typeof latency == 'number') {
this.latency = latency
cont = false
}
if (client_clock && typeof client_clock == 'number') {
this.clock_offset = Date.now() - client_clock - Math.floor(this.latency / 2)
cont = false
}
return cont
}
},
client: function (primus, options) {
primus.on('incoming::pong', options.use_clock_offset ? sendBoth : sendLatency)
primus.on('incoming::open', options.use_clock_offset ? sendBoth : sendLatency)
function sendLatency() {
this.write({ _latency: this.latency })
}
function sendBoth() {
this.write({ _latency: this.latency, _clock: Date.now() })
}
}
}