add listenOnClientConnectionChange to rtmt

This commit is contained in:
Halit Aksoy 2022-07-23 00:31:50 +03:00
parent b1a73167eb
commit 80d9401733
2 changed files with 11 additions and 1 deletions

View File

@ -1,8 +1,10 @@
export type Bytes = Buffer
export type OnMessage = (clientID: string, message: Object) => any
export type OnClientConnectionChange = (clientID: string, isOnline : boolean) => any
export interface RTMT {
sendMessage: (clientID: string, channel: string, message: Object) => any;
listenMessage: (channel: string, callback: OnMessage) => any;
isClientOnline(clientID: string): boolean;
listenOnClientConnectionChange(onUserConnectionChange: OnClientConnectionChange): void;
}

View File

@ -1,5 +1,5 @@
import { decode, encode } from "./encode_decode_message"
import { Bytes, OnMessage, RTMT } from "./rtmt"
import { Bytes, OnClientConnectionChange, OnMessage, RTMT } from "./rtmt"
import WebSocket from "ws"
import * as http from 'http';
@ -17,6 +17,8 @@ export class RTMTWS implements RTMT {
private pingInterval?: NodeJS.Timeout = undefined;
onUserConnectionChange?: OnClientConnectionChange;
constructor() {
this.messageChannels = new Map<String, OnMessage>()
this.wsServer = null
@ -32,6 +34,7 @@ export class RTMTWS implements RTMT {
const regexResult = req.url.split(RegExp("\/\?userKey="));
const clientID = regexResult[1]
this.clients.set(clientID, ws)
this.onUserConnectionChange?.(clientID, true);
ws.on("message", (messageBytes: string) => {
this.onWebSocketMessage(clientID, messageBytes)
})
@ -39,6 +42,7 @@ export class RTMTWS implements RTMT {
ws.on("close", (code: number, reason: string) => {
console.log("WS Closed! code : " + code + " reason : " + reason);
this.clients.delete(clientID)
this.onUserConnectionChange?.(clientID, false);
})
ws.on("error", (err: Error) => {
@ -130,4 +134,8 @@ export class RTMTWS implements RTMT {
isClientOnline(clientID: string): boolean {
return this.clients.has(clientID);
}
listenOnClientConnectionChange(onUserConnectionChange: OnClientConnectionChange) {
this.onUserConnectionChange = onUserConnectionChange;
}
}