feat: add KeepAlive packet
This commit is contained in:
+17
-1
@@ -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
@@ -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
|
||||
]
|
||||
|
||||
+1
-1
Submodule src/protocol updated: d0747faf68...1fe4783d94
Reference in New Issue
Block a user