Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

chore: live-data example WebSocket host (ws → addToDataset) (#3687)

Igor Dykhta878d96510081
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 490814969..820a0b709 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -33,7 +33,6 @@ Ref: http://keepachangelog.com/en/0.3.0/
- c45373a4 feat: reload and poll remotely hosted datasets (#3667)
- 30b0f648 feat: add GeoHash layer (#3666)
-
## [3.3.0-alpha.8] - Aug 26 2026
- af5d8173 chore: pin patched transitive deps via Yarn resolutions (#3654)
diff --git a/examples/README.md b/examples/README.md
index 08f970a23..97596cf94 100644
--- a/examples/README.md
+++ b/examples/README.md
@@ -52,7 +52,7 @@ yarn start
Read `visState.clicked` from Redux and show a GeoJSON feature's `shapeName` in a host-app sidebar outside the map.
- ### [Live Data][live-data]
- Remotely hosted CSV of points orbiting San Francisco on a 2-minute loop. Toggle **Poll URL** (HTTP snapshot replace every 300 ms) and **Host rows** (`addToDataset` / `removeFromDataset`, including upsert and delete by `id`, without rebuilding the point layer).
+ Remotely hosted CSV of points orbiting San Francisco on a 2-minute loop. Toggle **Poll URL** (HTTP snapshot replace every 300 ms), **Host rows** (`addToDataset` / `removeFromDataset`, including upsert and delete by `id`), and **WebSocket** (host maps `ws` upserts onto `addToDataset`; Kepler is not a websocket client).
- ### [Custom Layer][custom-layer]
Add a custom deck.gl layer (`ContourLayer`) to kepler.gl's layer type selector, so it can be picked from the dropdown, configured with dataset columns, and rendered on the map.
diff --git a/examples/live-data/README.md b/examples/live-data/README.md
index 309f6f9e8..d84373aea 100644
--- a/examples/live-data/README.md
+++ b/examples/live-data/README.md
@@ -1,7 +1,7 @@
# Live remotely hosted data
Loads a CORS CSV of points orbiting San Francisco as a remotely hosted dataset
-and **polls it every 300 ms**. The right sidebar switches between two host-app
+and **polls it every 300 ms**. The right sidebar switches between three host-app
update styles:
- **Poll URL** — HTTP snapshot replace (`refreshDataset` /
@@ -11,10 +11,14 @@ update styles:
`removeFromDataset` so rows change in place without tearing down the point
layer. Switching back to Poll URL resumes fetching and **replaces** the table
(injected rows disappear).
+- **WebSocket** — pauses the poll. The **host app** (not Kepler) opens
+ `ws://localhost:4010/vehicles.ws` and maps each JSON upsert to
+ `addToDataset(..., {upsertBy: 'id'})`. Kepler has no websocket client and
+ still rebuilds layer data on every message.
This bundles local monorepo `src/` (not a published npm package). Host-row
-edits only work for in-memory CSV (`RowDataContainer`), which this example
-uses. Arrow and DuckDB tables log a warning and leave the data unchanged
+and websocket edits only work for in-memory CSV (`RowDataContainer`), which this
+example uses. Arrow and DuckDB tables log a warning and leave the data unchanged
(INSERT / concat are not implemented yet). The **Keyed by id** controls
exercise `addToDataset(id, rows, {upsertBy: 'id'})` and
`removeFromDataset(id, {field: 'id', values})`.
@@ -60,6 +64,19 @@ run next to `yarn start` on 8080). The CSV server listens at
after 20 so the cloud stays bounded.
- Switch back to Poll URL: next CSV fetch restores the 3 orbiting vehicles.
+### WebSocket
+
+- Orbit **freezes**. The example host connects to
+ `ws://localhost:4010/vehicles.ws` (same process as the CSV server).
+- Server sends `{op: 'upsert', upsertBy: 'id', rows}` every 400ms. Three
+ `ws-01`…`ws-03` points (rings 8–10) complete a loop every **20 seconds**.
+ Row count grows by 3, then stays put while those ids move.
+- Sidebar shows socket status and message count. If the socket drops, the host
+ retries after 1s.
+- This is the [#322](https://github.com/keplergl/kepler.gl/issues/322) *transport*
+ pattern: `ws → addToDataset`. It is **not** a Kepler websocket layer and does
+ **not** skip a full layer-data rebuild.
+
## CSV server only (Add Data URL)
From this folder, or the repo root:
diff --git a/examples/live-data/esbuild.config.mjs b/examples/live-data/esbuild.config.mjs
index 6ae09f094..cfa1c024b 100644
--- a/examples/live-data/esbuild.config.mjs
+++ b/examples/live-data/esbuild.config.mjs
@@ -65,6 +65,9 @@ const config = {
define: {
NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development'),
'process.env.LIVE_DATA_URL': JSON.stringify(liveDataUrl),
+ 'process.env.LIVE_WS_URL': JSON.stringify(
+ process.env.LIVE_WS_URL || `ws://localhost:${dataPort}/vehicles.ws`
+ ),
'process.env.MapboxAccessToken': JSON.stringify(process.env.MapboxAccessToken || ''),
'process.env.DropboxClientId': JSON.stringify(process.env.DropboxClientId || ''),
'process.env.MapboxExportToken': JSON.stringify(process.env.MapboxExportToken || ''),
diff --git a/examples/live-data/server.mjs b/examples/live-data/server.mjs
index c34b8b02b..60233d3d6 100644
--- a/examples/live-data/server.mjs
+++ b/examples/live-data/server.mjs
@@ -14,9 +14,15 @@ import http from 'node:http';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
+import {attachWebSocketHub} from './websocket.mjs';
+
const DEFAULT_PORT = Number(process.env.LIVE_DATA_PORT || 4010);
const PERIOD_MS = Number(process.env.LIVE_DATA_PERIOD_MS || 120_000);
const POINT_COUNT = Number(process.env.LIVE_DATA_POINTS || 3);
+const WS_INTERVAL_MS = Number(process.env.LIVE_DATA_WS_INTERVAL_MS || 400);
+const WS_POINT_COUNT = Number(process.env.LIVE_DATA_WS_POINTS || 3);
+const WS_PATH = '/vehicles.ws';
+const WS_PERIOD_MS = 20_000;
const SF = {lat: 37.7749, lng: -122.4194};
const COS_LAT = Math.cos((SF.lat * Math.PI) / 180);
const KM_PER_DEG_LAT = 111.32;
@@ -88,6 +94,39 @@ function buildCsv(now = new Date()) {
return `${header}\n${rows.join('\n')}\n`;
}
+function wsVehicleAt(nowMs, index) {
+ const tau = (((nowMs % WS_PERIOD_MS) + WS_PERIOD_MS) % WS_PERIOD_MS) / WS_PERIOD_MS;
+ const radiusKm = 6.4 + index * 0.45;
+ const radiusLat = radiusKm / KM_PER_DEG_LAT;
+ const radiusLng = radiusKm / (KM_PER_DEG_LAT * COS_LAT);
+ const theta = tau * 2 * Math.PI + index * 1.7;
+ const lat = SF.lat + radiusLat * Math.sin(theta);
+ const lng = SF.lng + radiusLng * Math.cos(theta);
+ const heading = (((Math.atan2(-radiusLng * Math.sin(theta), radiusLat * Math.cos(theta)) * 180) /
+ Math.PI) +
+ 360) %
+ 360;
+ return {
+ id: `ws-${String(index + 1).padStart(2, '0')}`,
+ lat,
+ lng,
+ heading,
+ speed: ((2 * Math.PI * radiusKm) / (WS_PERIOD_MS / 1000)) * 3600,
+ ring: 8 + index,
+ progress: tau,
+ orbit_s: tau * (WS_PERIOD_MS / 1000),
+ updated_at: new Date(nowMs).toISOString()
+ };
+}
+
+function websocketPayload(nowMs = Date.now()) {
+ return {
+ op: 'upsert',
+ upsertBy: 'id',
+ rows: Array.from({length: WS_POINT_COUNT}, (_, index) => wsVehicleAt(nowMs, index))
+ };
+}
+
function serveCsv(req, res) {
const now = new Date();
const csv = buildCsv(now);
@@ -110,7 +149,7 @@ function serveCsv(req, res) {
res.end();
}
-function serveIndex(res) {
+function serveIndex(res, port) {
const tau = orbitProgress(Date.now());
const body = `<!DOCTYPE html>
<html>
@@ -121,9 +160,10 @@ function serveIndex(res) {
PERIOD_MS / 1000
}s (currently ${(tau * 100).toFixed(1)}% through the orbit).</p>
<ul>
- <li><a href="/vehicles.csv">/vehicles.csv</a> — positions at request time</li>
+ <li><a href="/vehicles.csv">/vehicles.csv</a> — paste this into Kepler.gl Add Data → URL, then set Refresh to Custom (0.3s)</li>
+ <li><code>ws://localhost:${port}${WS_PATH}</code> — JSON upserts for the live-data <strong>host app</strong> (not Add Data)</li>
</ul>
- <p>Paste that URL into Kepler.gl Add Data → URL, then set Refresh to 1s (or Custom) on the dataset.</p>
+ <p>The WebSocket URL is not a Kepler dataset source. Only the CSV belongs in Add Data → URL.</p>
</body>
</html>`;
res.writeHead(200, corsHeaders({'Content-Type': 'text/html; charset=utf-8'}));
@@ -143,19 +183,30 @@ export function startLiveDataServer(port = DEFAULT_PORT) {
return;
}
if (url.pathname === '/' || url.pathname === '/index.html') {
- serveIndex(res);
+ serveIndex(res, port);
return;
}
res.writeHead(404, corsHeaders({'Content-Type': 'text/plain'}));
res.end('Not found\n');
});
+ attachWebSocketHub(server, {
+ pathname: WS_PATH,
+ intervalMs: WS_INTERVAL_MS,
+ getPayload: () => websocketPayload()
+ });
+
server.listen(port, () => {
console.info(
`Live CSV at http://localhost:${port}/vehicles.csv (${POINT_COUNT} points, ${
PERIOD_MS / 1000
}s orbit)`
);
+ console.info(
+ `Live WebSocket at ws://localhost:${port}${WS_PATH} (${WS_POINT_COUNT} points, ${
+ WS_INTERVAL_MS
+ }ms upsert)`
+ );
});
return server;
diff --git a/examples/live-data/src/app.tsx b/examples/live-data/src/app.tsx
index dd7eaa6f4..f9575d0cc 100644
--- a/examples/live-data/src/app.tsx
+++ b/examples/live-data/src/app.tsx
@@ -26,6 +26,7 @@ const MAP_ID = 'map';
const SIDEBAR_WIDTH = 300;
const DATASET_ID = 'live-vehicles';
const LIVE_DATA_URL = process.env.LIVE_DATA_URL || 'http://localhost:4010/vehicles.csv';
+const LIVE_WS_URL = process.env.LIVE_WS_URL || 'ws://localhost:4010/vehicles.ws';
const REFRESH_INTERVAL_MS = 300;
const AUTO_INTERVAL_MS = 800;
const MAX_HOST_ROWS = 20;
@@ -37,7 +38,8 @@ const COS_LAT = Math.cos((SF.lat * Math.PI) / 180);
const KM_PER_DEG_LAT = 111.32;
const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));
-type LiveMode = 'poll' | 'host';
+type LiveMode = 'poll' | 'host' | 'ws';
+type WsStatus = 'idle' | 'connecting' | 'open' | 'closed' | 'error';
type KeplerRootState = {
keplerGl: {
@@ -191,7 +193,8 @@ function ModeToggle({
{(
[
['poll', 'Poll URL', true],
- ['host', 'Host rows', hostEnabled]
+ ['host', 'Host rows', hostEnabled],
+ ['ws', 'WebSocket', hostEnabled]
] as const
).map(([value, label, enabled]) => (
<button
@@ -207,7 +210,7 @@ function ModeToggle({
background: mode === value ? '#6a7485' : 'transparent',
color: enabled ? '#f7f7f7' : '#6a7485',
fontWeight: mode === value ? 600 : 400,
- fontSize: 13
+ fontSize: 12
}}
>
{label}
@@ -268,8 +271,8 @@ function PollSidebar({dataset}: {dataset: LiveDataset | undefined}) {
) : null}
<p style={{margin: '16px 0 0', color: '#c3c9d5'}}>
Layers panel: dataset refresh is 300ms. Click reload to sample the orbit immediately.
- Switching to <strong>Host rows</strong> pauses the poll so you can append or delete without
- the next snapshot wiping your edits.
+ Switching to <strong>Host rows</strong> or <strong>WebSocket</strong> pauses the poll so the
+ next snapshot does not wipe injected rows.
</p>
</>
);
@@ -411,6 +414,72 @@ function HostSidebar({
);
}
+function WsSidebar({
+ dataset,
+ status,
+ lastAt,
+ messageCount,
+ error
+}: {
+ dataset: LiveDataset | undefined;
+ status: WsStatus;
+ lastAt: number | null;
+ messageCount: number;
+ error: string | null;
+}) {
+ const rows = dataset?.dataContainer?.numRows?.() ?? 0;
+ const ids = rowIds(dataset);
+ const wsIds = ids.filter(id => id.startsWith('ws-'));
+
+ return (
+ <>
+ <p style={{margin: '0 0 12px', color: '#c3c9d5'}}>
+ Kepler.gl has no websocket client. This host opens <code>{LIVE_WS_URL}</code> and maps each
+ JSON message to <code>{"addToDataset(..., {upsertBy: 'id'})"}</code>. Three{' '}
+ <code>ws-*</code> points (rings 8–10) move on a 20s loop. Layer id and style stay put;
+ Kepler still rebuilds layer data on every message.
+ </p>
+ <div style={{display: 'grid', gap: 8, marginBottom: 12}}>
+ <div style={{display: 'flex', justifyContent: 'space-between', gap: 12}}>
+ <span style={{color: '#c3c9d5'}}>socket</span>
+ <span>{status}</span>
+ </div>
+ <div style={{display: 'flex', justifyContent: 'space-between', gap: 12}}>
+ <span style={{color: '#c3c9d5'}}>messages</span>
+ <span>{messageCount}</span>
+ </div>
+ <div style={{display: 'flex', justifyContent: 'space-between', gap: 12}}>
+ <span style={{color: '#c3c9d5'}}>last upsert</span>
+ <span>{lastAt ? new Date(lastAt).toLocaleTimeString() : '—'}</span>
+ </div>
+ <div style={{display: 'flex', justifyContent: 'space-between', gap: 12}}>
+ <span style={{color: '#c3c9d5'}}>rows</span>
+ <span>
+ {rows} <span style={{color: '#c3c9d5'}}>({wsIds.length} ws)</span>
+ </span>
+ </div>
+ <div
+ style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ gap: 12,
+ alignItems: 'flex-start'
+ }}
+ >
+ <span style={{color: '#c3c9d5', flexShrink: 0}}>ws ids</span>
+ <span style={{textAlign: 'right', wordBreak: 'break-word'}}>
+ {wsIds.length ? wsIds.join(', ') : '—'}
+ </span>
+ </div>
+ </div>
+ {error ? <p style={{margin: '0 0 12px', color: '#f19c99'}}>{error}</p> : null}
+ <p style={{margin: 0, color: '#c3c9d5'}}>
+ Switch back to <strong>Poll URL</strong> to close the socket and restore the 3 CSV vehicles.
+ </p>
+ </>
+ );
+}
+
function LiveDataSidebar() {
const dispatch = useDispatch();
const dataset = useSelector(
@@ -419,6 +488,10 @@ function LiveDataSidebar() {
const [mode, setMode] = useState<LiveMode>('poll');
const [autoTrail, setAutoTrail] = useState(false);
const [keyedNote, setKeyedNote] = useState('');
+ const [wsStatus, setWsStatus] = useState<WsStatus>('idle');
+ const [wsLastAt, setWsLastAt] = useState<number | null>(null);
+ const [wsCount, setWsCount] = useState(0);
+ const [wsError, setWsError] = useState<string | null>(null);
const hostSeq = useRef(1);
const trackSeq = useRef(1);
const datasetRef = useRef(dataset);
@@ -435,12 +508,20 @@ function LiveDataSidebar() {
if (next === 'poll') {
setAutoTrail(false);
setKeyedNote('');
+ setWsStatus('idle');
+ setWsError(null);
toKepler(
updateDatasetProps(DATASET_ID, {metadata: {refreshIntervalMs: REFRESH_INTERVAL_MS}})
);
toKepler(refreshDataset(DATASET_ID));
return;
}
+ setAutoTrail(false);
+ if (next === 'ws') {
+ setWsCount(0);
+ setWsLastAt(null);
+ setWsError(null);
+ }
toKepler(updateDatasetProps(DATASET_ID, {metadata: {refreshIntervalMs: 0}}));
},
[toKepler]
@@ -516,6 +597,67 @@ function LiveDataSidebar() {
return () => window.clearInterval(timer);
}, [autoTrail, mode, toKepler]);
+ useEffect(() => {
+ if (mode !== 'ws') {
+ setWsStatus(current => (current === 'idle' ? current : 'idle'));
+ return undefined;
+ }
+
+ let cancelled = false;
+ let retryTimer: number | undefined;
+ let socket: WebSocket | null = null;
+
+ const connect = () => {
+ if (cancelled) {
+ return;
+ }
+ setWsStatus('connecting');
+ setWsError(null);
+ socket = new WebSocket(LIVE_WS_URL);
+ socket.onopen = () => {
+ if (!cancelled) {
+ setWsStatus('open');
+ }
+ };
+ socket.onmessage = event => {
+ let message: {op?: string; rows?: unknown; upsertBy?: string};
+ try {
+ message = JSON.parse(String(event.data));
+ } catch {
+ return;
+ }
+ if (message.op !== 'upsert' || !message.rows) {
+ return;
+ }
+ toKepler(addToDataset(DATASET_ID, message.rows, {upsertBy: message.upsertBy || 'id'}));
+ setWsCount(count => count + 1);
+ setWsLastAt(Date.now());
+ };
+ socket.onerror = () => {
+ if (!cancelled) {
+ setWsStatus('error');
+ setWsError(`Could not open ${LIVE_WS_URL}`);
+ }
+ };
+ socket.onclose = () => {
+ if (cancelled) {
+ return;
+ }
+ setWsStatus('closed');
+ retryTimer = window.setTimeout(connect, 1000);
+ };
+ };
+
+ connect();
+ return () => {
+ cancelled = true;
+ if (retryTimer) {
+ window.clearTimeout(retryTimer);
+ }
+ socket?.close();
+ };
+ }, [mode, toKepler]);
+
return (
<aside style={sidebarStyle}>
<h2 style={{margin: '0 0 8px', fontSize: 16}}>Live data</h2>
@@ -526,6 +668,14 @@ function LiveDataSidebar() {
/>
{mode === 'poll' ? (
<PollSidebar dataset={dataset} />
+ ) : mode === 'ws' ? (
+ <WsSidebar
+ dataset={dataset}
+ status={wsStatus}
+ lastAt={wsLastAt}
+ messageCount={wsCount}
+ error={wsError}
+ />
) : (
<HostSidebar
dataset={dataset}
diff --git a/examples/live-data/websocket.mjs b/examples/live-data/websocket.mjs
new file mode 100644
index 000000000..2a25c367d
--- /dev/null
+++ b/examples/live-data/websocket.mjs
@@ -0,0 +1,165 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+/**
+ * Minimal WebSocket hub for the live-data example (no extra npm dependency).
+ * Text frames only. Good enough to demo host-app `ws → addToDataset`.
+ */
+import crypto from 'node:crypto';
+
+const ACCEPT_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
+const OP_TEXT = 0x1;
+const OP_CLOSE = 0x8;
+const OP_PING = 0x9;
+const OP_PONG = 0xa;
+
+function acceptKey(secWebSocketKey) {
+ return crypto.createHash('sha1').update(`${secWebSocketKey}${ACCEPT_GUID}`).digest('base64');
+}
+
+function encodeFrame(opcode, payload) {
+ const body = Buffer.isBuffer(payload) ? payload : Buffer.from(payload);
+ const len = body.length;
+ let header;
+ if (len < 126) {
+ header = Buffer.alloc(2);
+ header[0] = 0x80 | opcode;
+ header[1] = len;
+ } else if (len < 65536) {
+ header = Buffer.alloc(4);
+ header[0] = 0x80 | opcode;
+ header[1] = 126;
+ header.writeUInt16BE(len, 2);
+ } else {
+ header = Buffer.alloc(10);
+ header[0] = 0x80 | opcode;
+ header[1] = 127;
+ header.writeBigUInt64BE(BigInt(len), 2);
+ }
+ return Buffer.concat([header, body]);
+}
+
+function readFrames(buffer) {
+ const frames = [];
+ let offset = 0;
+ while (offset + 2 <= buffer.length) {
+ const second = buffer[offset + 1];
+ const masked = Boolean(second & 0x80);
+ let len = second & 0x7f;
+ let pos = offset + 2;
+ if (len === 126) {
+ if (pos + 2 > buffer.length) {
+ break;
+ }
+ len = buffer.readUInt16BE(pos);
+ pos += 2;
+ } else if (len === 127) {
+ if (pos + 8 > buffer.length) {
+ break;
+ }
+ len = Number(buffer.readBigUInt64BE(pos));
+ pos += 8;
+ }
+ const maskBytes = masked ? 4 : 0;
+ if (pos + maskBytes + len > buffer.length) {
+ break;
+ }
+ const opcode = buffer[offset] & 0x0f;
+ let payload = buffer.subarray(pos + maskBytes, pos + maskBytes + len);
+ if (masked) {
+ const mask = buffer.subarray(pos, pos + 4);
+ payload = Buffer.from(payload);
+ for (let i = 0; i < payload.length; i++) {
+ payload[i] ^= mask[i % 4];
+ }
+ }
+ frames.push({opcode, payload});
+ offset = pos + maskBytes + len;
+ }
+ return {frames, rest: buffer.subarray(offset)};
+}
+
+/**
+ * Upgrade GET requests on `pathname` and broadcast `getPayload()` JSON to
+ * every connected client on `intervalMs`.
+ */
+export function attachWebSocketHub(server, {pathname, intervalMs, getPayload}) {
+ const clients = new Set();
+
+ server.on('upgrade', (req, socket, head) => {
+ const url = new URL(req.url || '/', 'http://127.0.0.1');
+ if (url.pathname !== pathname) {
+ socket.write('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n');
+ socket.destroy();
+ return;
+ }
+ const key = req.headers['sec-websocket-key'];
+ if (req.headers.upgrade !== 'websocket' || !key) {
+ socket.write('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n');
+ socket.destroy();
+ return;
+ }
+
+ socket.write(
+ [
+ 'HTTP/1.1 101 Switching Protocols',
+ 'Upgrade: websocket',
+ 'Connection: Upgrade',
+ `Sec-WebSocket-Accept: ${acceptKey(key)}`,
+ '',
+ ''
+ ].join('\r\n')
+ );
+ if (head?.length) {
+ socket.unshift(head);
+ }
+
+ const client = {socket, buffer: Buffer.alloc(0)};
+ clients.add(client);
+
+ const drop = () => {
+ clients.delete(client);
+ socket.destroy();
+ };
+
+ socket.on('data', chunk => {
+ client.buffer = Buffer.concat([client.buffer, chunk]);
+ const {frames, rest} = readFrames(client.buffer);
+ client.buffer = rest;
+ for (const frame of frames) {
+ if (frame.opcode === OP_CLOSE) {
+ try {
+ socket.write(encodeFrame(OP_CLOSE, frame.payload));
+ } catch {
+ // ignore
+ }
+ drop();
+ return;
+ }
+ if (frame.opcode === OP_PING) {
+ socket.write(encodeFrame(OP_PONG, frame.payload));
+ }
+ }
+ });
+ socket.on('error', drop);
+ socket.on('close', drop);
+ });
+
+ const timer = setInterval(() => {
+ if (!clients.size) {
+ return;
+ }
+ const frame = encodeFrame(OP_TEXT, JSON.stringify(getPayload()));
+ for (const client of clients) {
+ try {
+ client.socket.write(frame);
+ } catch {
+ clients.delete(client);
+ client.socket.destroy();
+ }
+ }
+ }, intervalMs);
+
+ server.on('close', () => clearInterval(timer));
+ return {clients, timer};
+}