Merge pull request #22 from jhalitaksoy/feature/ping-pong

Feature/ping pong
This commit is contained in:
Halit Aksoy 2022-07-16 22:31:22 +03:00 committed by GitHub
commit 5f9d983df6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 1 deletions

View File

@ -6,3 +6,5 @@ export const channel_leave_game = "leave_game"
export const channel_on_game_end = "on_game_end"
export const channel_on_game_crashed = "on_game_crashed"
export const channel_on_game_user_leave = "on_game_user_leave"
export const channel_ping = "ping"
export const channel_pong = "pong"

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) {