UNPKG

ws-heartbeat

Version:

Server-side and client-side heartbeat library for ws and browser-side Websocket.

51 lines (50 loc) 1.79 kB
"use strict"; var __values = (this && this.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.setWsHeartbeat = void 0; function setWsHeartbeat(wss, pong, pingTimeout) { if (pingTimeout === void 0) { pingTimeout = 60000; } var connections = new Set(); wss.addListener("connection", function (ws) { connections.add(ws); ws.addListener("message", function (data) { connections.add(ws); pong(ws, data, typeof data !== "string"); }); }); var handle = setInterval(function () { var e_1, _a; try { for (var _b = __values(wss.clients), _c = _b.next(); !_c.done; _c = _b.next()) { var ws = _c.value; if (ws.readyState === ws.CONNECTING || ws.readyState === ws.OPEN) { if (!connections.has(ws)) { ws.close(); } } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } connections.clear(); }, pingTimeout); wss.addListener("close", function () { clearInterval(handle); }); } exports.setWsHeartbeat = setWsHeartbeat;