feat: add KeepAlive packet

This commit is contained in:
2023-07-15 14:15:14 +02:00
parent 6953d870ae
commit 5576093c18
3 changed files with 24 additions and 5 deletions
+17 -1
View File
@@ -6,7 +6,8 @@ import {
PublishRequest,
PublishResponse,
DiscoverRequest,
DiscoverResponse
DiscoverResponse,
KeepAlive
} from './Protocol.js'
import { EventEmitter } from 'events'
@@ -17,6 +18,8 @@ export class Client extends EventEmitter {
#ws
#id
#address
#keepAliveInterval
#lastPacketDate = 0
constructor(gateway) {
super()
@@ -33,6 +36,8 @@ export class Client extends EventEmitter {
const buf = Container.encode(container).finish()
console.log('sending:', buf)
this.#ws.send(buf)
this.#lastPacketDate = Date.now()
}
#protoRequest(message) {
@@ -67,6 +72,15 @@ export class Client extends EventEmitter {
const auth = AuthenticationResponse.toObject(response.AuthenticationResponse, { longs: String })
this.#address = BigInt(auth.address)
// send packets periodically to keep the connection alive
this.#keepAliveInterval = setInterval(async () => {
if ((Date.now() - this.#lastPacketDate) > 30000) {
await this.#protoRequest(KeepAlive.create({
data: Date.now()
}))
}
}, 15000)
this.emit('ready')
}
@@ -81,6 +95,8 @@ export class Client extends EventEmitter {
ws.onclose = () => {
this.emit('close')
clearInterval(this.#keepAliveInterval)
this.#keepAliveInterval = null
}
}
+6 -3
View File
@@ -18,7 +18,8 @@ export const [
PublishRequest,
PublishResponse,
DiscoverRequest,
DiscoverResponse
DiscoverResponse,
KeepAlive
] = import_proto(encoders, [
'Container',
'AuthenticationRequest',
@@ -27,7 +28,8 @@ export const [
'PublishRequest',
'PublishResponse',
'DiscoverRequest',
'DiscoverResponse'
'DiscoverResponse',
'KeepAlive'
])
export const messages = [
@@ -38,5 +40,6 @@ export const messages = [
PublishRequest,
PublishResponse,
DiscoverRequest,
DiscoverResponse
DiscoverResponse,
KeepAlive
]