From 5966bb8c9e947cf0bb5a5a41b91f8c331ae548f5 Mon Sep 17 00:00:00 2001 From: Jeongho Nam Date: Mon, 29 Jul 2024 14:47:46 +0900 Subject: [PATCH] New function `WebSocketAcceptor.ping()` --- package.json | 2 +- src/protocols/web/WebSocketAcceptor.ts | 28 ++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index ce9c4ab..005c894 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "tgrid", - "version": "1.0.2", + "version": "1.0.3", "main": "lib/index.js", "typings": "lib/index.d.ts", "exports": { diff --git a/src/protocols/web/WebSocketAcceptor.ts b/src/protocols/web/WebSocketAcceptor.ts index dc0ca8d..224a7c2 100644 --- a/src/protocols/web/WebSocketAcceptor.ts +++ b/src/protocols/web/WebSocketAcceptor.ts @@ -1,4 +1,5 @@ import type http from "http"; +import { sleep_for } from "tstl"; import type WebSocket from "ws"; import { Invoke } from "../../components/Invoke"; @@ -240,6 +241,33 @@ export class WebSocketAcceptor< /* ---------------------------------------------------------------- COMMUNICATOR ---------------------------------------------------------------- */ + /** + * Ping to the remote client. + * + * Send a ping message to the remote client repeatedly. + * + * The ping message would be sent every internal milliseconds, until the + * connection be disconnectedd. The remote client will reply with a pong + * message, so that the connection would be alive until be explicitly + * disconnected. + * + * @param ms Interval milliseconds + * @throws Error when the connection is not accepted. + */ + public ping(ms: number): void { + // TEST CONDITION + const error: Error | null = this.inspectReady("close"); + if (error) throw error; + (async (): Promise => { + while (this.state_ === WebSocketAcceptor.State.OPEN) { + await sleep_for(ms); + try { + this.socket_.ping(); + } catch {} + } + })().catch(() => {}); + } + /** * @hidden */