fix connection time syncing handling
Share the time syncing code, and while we're at it wrap the whole connection thing in a class. Makes it easier to pass the connection around & later on add more advanced handler registration if we want to.
This commit is contained in:
parent
f900542765
commit
9e7000054b
3 changed files with 132 additions and 112 deletions
|
|
@ -105,11 +105,58 @@ export function session_id() {
|
|||
return match ? match[1] : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Guess the exact current server time.
|
||||
*/
|
||||
export function servertime_now_ns() {
|
||||
const now_ms = performance.now()
|
||||
const delta_ns = ms_ns * (now_ms - toffset_ms)
|
||||
return servertime + delta_ns
|
||||
export class Connection {
|
||||
constructor() {
|
||||
this.socket = null
|
||||
this.toffset_ms = null
|
||||
this.servertime = null
|
||||
this.handlers = {
|
||||
time: this._handler_time.bind(this),
|
||||
error: this._handler_error.bind(this),
|
||||
}
|
||||
}
|
||||
|
||||
_handler_time({ value: { time } }) {
|
||||
this.servertime = time
|
||||
this.toffset_ms = performance.now()
|
||||
}
|
||||
|
||||
_handler_error({ value: { reason } }) {
|
||||
console.error(`Error: ${reason}`)
|
||||
}
|
||||
|
||||
connect(url) {
|
||||
this.socket = new WebSocket(url)
|
||||
this.socket.addEventListener("open", (event) => {
|
||||
if ("helo" in this.handlers) {
|
||||
this.handlers["helo"](event)
|
||||
}
|
||||
})
|
||||
this.socket.addEventListener("message", (event) => {
|
||||
const msg = JSON.parse(event.data)
|
||||
if (msg.type in this.handlers) {
|
||||
this.handlers[msg.type](msg)
|
||||
} else {
|
||||
console.error(`Unhandled message: ${event.data}`)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
on(type, callback) {
|
||||
this.handlers[type] = callback
|
||||
}
|
||||
|
||||
/**
|
||||
* Guess the exact current server time.
|
||||
*/
|
||||
servertime_now_ns() {
|
||||
const now_ms = performance.now()
|
||||
const delta_ns = ms_ns * (now_ms - this.toffset_ms)
|
||||
return this.servertime + delta_ns
|
||||
}
|
||||
|
||||
send(type, value) {
|
||||
// console.debug('sending', value)
|
||||
this.socket.send(JSON.stringify({ type, value }))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue