Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - How to close WebSocketSubject underlying socket

Is there a way to obtain the socket being subscribed by WebSocketSubject?

When a certain condition happens I need to close the underlying socket.

I tried to close it by complete() but it didn't close the socket. The unsubscribed doesn't work either.

Could anybody help me? Or point me in the right direction?

like image 205
ThelmaJay Avatar asked Feb 14 '26 09:02

ThelmaJay


1 Answers

He said that the unsubscribe did not work. Indeed I had the same problem. I was doing the unsubscribe and it wasn't closed.

I end up using directly the websocket instead of WebSocketSubject, so I could call the method close (which worked).

         this._ws = new WebSocket(this.url);
         this.messages = Observable.create((observer) => {
             this._ws.addEventListener('message', (message) => (
                // Et on ajoute chaque message dans l'Observable
                observer.next(message)
              ), false);

              // On s'enregistre au erreurs qui surviendraient
              // dans la websocket
              this._ws.addEventListener('error', (error) => {
                // Si un erreur est survenue, on prévient
                // l'Observable
                console.log('error ws');

                observer.error(error)

              }, false);

              // On s'enregistre à la fermeture du websocket
              this._ws.addEventListener('close', () => {
                // On met fin à l'Observable
                observer.complete()

                console.log('complete');
              }, false)
         })
    ... 

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

I follow this tuto Introduction à RxJS and this one

If you manage to do a reconnect after the server closes the WS, please post it also.

Thanks

like image 64
Javier Avatar answered Feb 16 '26 23:02

Javier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!