How to prevent websocket from closing after a certain time in angular5?

I use 'rxjs-websockets' to connect to websockets. But after a certain time (approximately 2 minutes), the connection closes. How can I hold the connection until it is closed manually.

Here is the code snippet I am using

constructor(private socketService: WebSocketService) {}

this.socketService.connect('/endpoint');
this.socketSubscription = this.socketService.messages
      .subscribe(result => {            
            // perform operation
    });

This is a WebSocketService

import {Injectable} from '@angular/core';
import {QueueingSubject} from 'queueing-subject';
import {Observable} from 'rxjs/Observable';
import websocketConnect from 'rxjs-websockets';
import 'rxjs/add/operator/share';
import 'rxjs/add/operator/retryWhen';
import 'rxjs/add/operator/delay';

@Injectable()
export class WebSocketService {
  private inputStream: QueueingSubject<string>;
  public messages: Observable<string>;

  constructor() {    
  }

  public connect(socketUrl) {
      this.messages = websocketConnect(
        socketUrl,
        this.inputStream = new QueueingSubject<string>()
      ).messages.retryWhen(errors => errors.delay(1000))
        .map(message => JSON.parse(message))
        .share();
  }

  public send(message: string): void {
    this.inputStream.next(message);
  }
}
+4
source share
1 answer

Websockets typically maintains a connection for a long period using messaging. In our case, we can call it "ping => pong", the client sends the message "ping", and the server can respond with the message "pong".

You can send ping every 30 seconds as follows.

setInterval(() => {
    this.socketService.send('ping');
}, 30000);

, WebSocketService JSON, JSON Parsing.

export class WebSocketService {
.
.
.

    public connect(socketUrl) {
      this.messages = websocketConnect(
        socketUrl,
        this.inputStream = new QueueingSubject<string>()
      ).messages.retryWhen(errors => errors.delay(1000))
        //parse messages except pong to avoid JSON parsing error
        .map(message => message === 'pong' ? message : JSON.parse(message))
        .share();
    }
.
.
.
}
+5

Source: https://habr.com/ru/post/1694897/


All Articles