Mohit Harshan
Mohit Harshan

Reputation: 1986

reconnect web socket if it is closed

My web socket connection code :

  public connect(): Subject<MessageEvent> {
    if (!this.subject) {
      this.subject = this.create(this.url);

    }
    this.ws.onerror = () => {
      this.close();
      let refresh = setInterval(() => {
        this.subject = null;
        this.connect();
        this.ws.onopen = () => {
          clearInterval(refresh)
        }
      }, 5000);
    }

    return this.subject;
  }

  private create(url: string){
    this.ws = new WebSocket(url);
    const observable = Observable.create((obs: Subject<MessageEvent>) => {
      this.ws.onmessage = obs.next.bind(obs);
      this.ws.onerror = obs.error.bind(obs);
      this.ws.onclose = obs.complete.bind(obs);
      this.ws.onclose = function () {
        console.log("trying to reconnect");
        this.connect();
      }

      return this.ws.close.bind(this.ws);
    });

    const observer = {
      next: (data: any) => {
        if (this.ws.readyState === WebSocket.OPEN) {
          this.ws.send(JSON.stringify(data));
        }
      }
    };
    return Subject.create(observer, observable);
  }

I want to reconnect web socket if connection closes. At the moment the function gets truggered when i stop the web socket. BUt is not connecting again .I See error "this.connect is not a function" .How to work with angular recursive functions?

Upvotes: 0

Views: 358

Answers (1)

Trash Can
Trash Can

Reputation: 6824

Don't use function keyword to create your callback when using this inside of it if you aren't aware of how it changes the this reference depending on the execution context, use arrow function instead

To make it reconnect, change this

this.ws.onclose = function () {
    console.log("trying to reconnect");
    this.connect();
}

To this

this.ws.onclose = () => {
    console.log("trying to reconnect");
    this.subject = null;
    this.connect();
}

Upvotes: 1

Related Questions