So, you use websocket (lib "ws").
You can rewrite your service
// socket-client.ts
import { Injectable } from "@nestjs/common";
import * as WebSocket from "ws";
import {timer} from 'rxjs'
@Injectable()
export class WSService {
// wss://echo.websocket.org is a test websocket server
private ws: WebSocket;
private isConnect = false;
constructor() {
this.connect()
}
connect(){
this.ws = new WebSocket("wss://echo.websocket.org");
this.ws.on("open", () => {
this.isConnect = true;
this.ws.send(Math.random())
});
this.ws.on("error", (message) => {
this.ws.close()
this.isConnect = false;
});
this.ws.on("close", (message) => {
timer(1000).subscribe(() => {
this.isConnect = false;
this.connect();
})
});
this.ws.on("message", (message) => {
//handler
});
}
send(data: any) {
this.ws.send(data);
}
getIsConnect(){
return this.isConnect;
}
}
you use function connect() to create new connection. And when connection error, you close it, and when close connection, you will trigger timer wait 1s then reconnect.
This is simplest way to implement reconnect with ws, but in fact there are many reason that make socket disconnect, or server forget you. You must implement ping-pong to make sure server not forget you, or interval check isConnect then re-connect
or you can use socket-io.client because it handle re-connect automatic for you. But require server implement socket-io too.
You can read more in https://stackoverflow.com/a/23176223/4397117