add ping pong

This commit is contained in:
Halit Aksoy 2022-07-16 17:16:41 +03:00
parent 1530592e3e
commit 2e584fff32

View File

@ -1,11 +1,16 @@
import { decode, encode } from "./encode_decode_message";
import { Bytes, OnMessage, RTMT } from "./rtmt";
import { server } from "../service/http_service";
import { channel_ping, channel_pong } from "../const/channel_names";
const PING_INTERVAL = 3000, PING_INTERVAL_BUFFER_TIME = 500;
export class RTMTWS implements RTMT {
private messageChannels: Map<String, OnMessage>;
private ws: WebSocket;
private pingTimeout?: number = undefined;
constructor() {
this.messageChannels = new Map<String, OnMessage>();
}
@ -22,11 +27,13 @@ export class RTMTWS implements RTMT {
ws.onopen = () => {
console.info("(RTMT) ws has opened");
this.ws = ws;
this.heartbeat();
onopen();
};
ws.onclose = () => {
console.info("(RTMT) ws has closed");
//this.ws = undefined
clearTimeout(this.pingTimeout);
onClose();
};
@ -40,6 +47,20 @@ export class RTMTWS implements RTMT {
});
}
heartbeat() {
clearTimeout(this.pingTimeout);
// Use `WebSocket#terminate()`, which immediately destroys the connection,
// instead of `WebSocket#close()`, which waits for the close timer.
// Delay should be equal to the interval at which your server
// sends out pings plus a conservative assumption of the latency.
this.pingTimeout = setTimeout(() => {
this.ws.close();
this.ws.onclose?.(new CloseEvent("CONNECTION_LOST"));
}, PING_INTERVAL + PING_INTERVAL_BUFFER_TIME);
}
sendMessage(channel: string, message: Object) {
if (this.ws === undefined) {
console.error("(RTMT) ws is undefined");
@ -59,6 +80,11 @@ export class RTMTWS implements RTMT {
}
onMessage(channel: string, message: Bytes) {
if(channel === channel_ping) {
this.heartbeat();
this.sendMessage(channel_pong, {});
return;
}
const callback = this.messageChannels.get(channel);
if (callback) {