0

I found this answer Connect NestJS to a websocket server

Implemented my client as what you would have in the first answer. Second answer vent over my head a bit. Now I have a problem with listeners. When the socket disconnects I want to reconnect again. As you can see in the example listeners are instantiated in the constructor. When I want to reconnect those listeners are not re-instantiated and I don't know how to achieve that. Or how to instantiate listeners in some other way? Or even how to destroy that service and build a new one?

1 Answer 1

1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.