Skip to content

Commit 709f01b

Browse files
Added automatic reconnect to WebSocket (#33)
1 parent ada2b48 commit 709f01b

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

src/components/LazyLog/index.tsx

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,15 @@ export interface WebsocketOptions {
3939
* Callback allback which formats the websocket data stream.
4040
*/
4141
formatMessage?: ((message: any) => string) | undefined;
42+
/**
43+
* Set to true, to reconnect the WebSocket automatically.
44+
*/
45+
reconnect?: boolean;
46+
/**
47+
* Set the time to wait between reconnects in seconds.
48+
* Default is 1s
49+
*/
50+
reconnectWait?: number
4251
}
4352

4453
export interface ErrorStatus extends Error {

src/components/Utils/websocket.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ export default (url: string | URL, options: WebsocketOptions) => {
1010
const emitter = mitt();
1111
let encodedLog = new Uint8Array();
1212
let overage: any = null;
13+
let aborted: boolean = false;
1314

1415
emitter.on("data", (data) => {
1516
encodedLog = bufferConcat(
@@ -46,6 +47,10 @@ export default (url: string | URL, options: WebsocketOptions) => {
4647
});
4748
socket.addEventListener("close", (e) => {
4849
onClose && onClose(e);
50+
if(!aborted && options.reconnect) {
51+
const timeout = options.reconnectWait ?? 1;
52+
setTimeout(() => emitter.emit("start"), timeout*1000);
53+
}
4954
});
5055

5156
socket.addEventListener("error", (err) => {
@@ -65,7 +70,10 @@ export default (url: string | URL, options: WebsocketOptions) => {
6570
emitter.emit("data", msg);
6671
});
6772

68-
emitter.on("abort", () => socket.close());
73+
emitter.on("abort", () => {
74+
aborted = true;
75+
socket.close()
76+
});
6977
} catch (err) {
7078
emitter.emit("error", err);
7179
}

0 commit comments

Comments
 (0)