Angular4 Websocket rxjs Reconnect and onError

帅比萌擦擦* 提交于 2019-12-02 08:06:21

Well, I found a way. I'm using the old approach with Observable.websocket

@Injectable()
export class WSMyService {
    private url: string = '';
    static readonly ID = 'mytestwebsocket';
    readonly reload_time = 3000;

    public messages: Observable<any>;
    private ws: Subject<any>;
    public onclose = new Subject();
    constructor(private configService: ConfigService) {
        console.log('constructor ws synop service')
        this.setUrl(WSActionFrontService.ID)
    }

    public setUrl(id:string) {
        ...
        this.url = `ws://${host}:${port}/` + id 
    }

    public connect(): Observable<any> {
      this.ws = Observable.webSocket({
        url: this.url,
        closeObserver: this.onclose
      });
      return this.messages = this.ws.retryWhen(errors => errors.delay(this.reload_time)).map(msg => msg).share();
    }

    send(msg: any) {
      this.ws.next(JSON.stringify(msg));
    }

    public close() {
        console.log('on closing WS');
        this.ws.complete();
    }

and when I use it:

constructor(
    private wsMyService: WSMyService,

ngOnInit():
  ...
  this.mySocketSubscription = this.wsMyService.connect().subscribe(message => {
 ... }
  this.wsMyService.onclose.subscribe(evt => {
  // the server has closed the connection
  })

ngOnDestroy() {

    this.wsMyService.close();
    this.mySocketSubscription.unsubscribe();
    ...
}

Looks like all I had to do was to call the function complete() which tells the server that the client has finished. I'm sure there is a better way, but this is the only one I found that works for me.

Thank you for your help.

You don't have any way to know when server close connection with client.

As you have notice,this._ws.onclose = obs.complete.bind(obs); Will be fire only when 'close' action is done by client.

Common way to play around :

  • onClose of your server, you send special message to all your clients to notify it.
  • Create ping mechanic to ask server if he is still alive.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!