Skip to content

Commit

Permalink
feat: add delay timer when try to reconncet (#23)
Browse files Browse the repository at this point in the history
* feat: add delay timer when try to reconncet

* update tests
  • Loading branch information
wqcstrong committed Dec 14, 2023
1 parent 2c84649 commit b229dd6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 12 deletions.
11 changes: 10 additions & 1 deletion src/utils/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ export class SocketStore {

private timer: number | null = null;

private retryTimer: number | null = null;

// messages store
private messages: (SpySocket.BroadcastEvent | SpySocket.UnicastEvent)[] = [];

Expand Down Expand Up @@ -142,7 +144,14 @@ export class SocketStore {
return;
}

this.tryReconnect();
if (this.retryTimer) {
clearTimeout(this.retryTimer);
}

this.retryTimer = window.setTimeout(() => {
this.retryTimer = null;
this.tryReconnect();
}, 2000);
}

tryReconnect() {
Expand Down
26 changes: 15 additions & 11 deletions tests/utils/socket.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,22 +29,26 @@ describe('Socket store', () => {
expect(client.connectionStatus).toBe(true);
client.getSocket()?.close();

await sleep();
await sleep(2000 + 500);
expect(reconnect).toHaveBeenCalledTimes(1);
expect(client.connectionStatus).toBe(true);
});

it('Connect failed if reconnect over 3 times', async () => {
// @ts-ignore
expect(client.reconnectTimes).toBe(3);
server.close();
it(
'Connect failed if reconnect over 3 times',
async () => {
// @ts-ignore
expect(client.reconnectTimes).toBe(3);
server.close();

await sleep(300);
// @ts-ignore
expect(client.reconnectTimes).toBe(0);
// @ts-ignore
expect(client.reconnectable).toBe(false);
});
await sleep(2000 * 3);
// @ts-ignore
expect(client.reconnectTimes).toBe(0);
// @ts-ignore
expect(client.reconnectable).toBe(false);
},
2000 * 4,
);

it('Stop', async () => {
expect(client.connectionStatus).toBe(true);
Expand Down

0 comments on commit b229dd6

Please sign in to comment.