问题
It looks like there are several similar questions but after several days I do not find the proper answer. My question is how to know if the server has closed the websocket and how to try to reconnect. I have seen several examples but none of them worked properly when I wanted to implement the fonctionality of closing the websocket from the client when I change the view.
Then I found this example which it's the best one I have seen so far, and with a small modifications I was able to add a close function which works quite well.
Closing the websocket from the client is not a problem anymore, however, I am not able to know when the websocket is closed by the server and how to reconnect again.
My code is very similar to this question but I am asking for a different thing. Also, I had problems re-using the websocket until I saw the share function that they talk in the link I put, so in the class I have posted, the websocket service and the service which used the websocket service are the merged in one
My websocket service
import { Injectable } from '@angular/core';
import { Observable, Observer, Subscription } from 'rxjs';
import { Subject } from 'rxjs/Subject';
import { ConfigService } from "../config.service";
@Injectable()
export class WSEtatMachineService {
public messages: Subject<any> = new Subject<any>();
private url: string = '';
static readonly ID = 'machine';
private _subject: Subject<MessageEvent>;
private _subjectData: Subject<number>;
private _ws: any;
constructor(private configService: ConfigService) {
console.log('constructyor ws machine service')
this.setUrl(WSEtatMachineService.ID)
}
public setUrl(id:string) {
const host = this.configService.getConfigReseau().ipServer;
const port = this.configService.getConfigReseau().portServer;
this.url = `ws://${host}:${port}/` + id
}
public connect() {
console.log('connect ws machine service ', this.url)
this.messages = <Subject<any>>this._connect(this.url)
.map((response: any): any => {
console.log('ws etat machine service: ', response)
return JSON.parse(response.data);
})
}
public close() {
console.log('on closing WS');
this._ws.close()
this._subject = null
}
public send(msg: any) {
this.messages.next(JSON.stringify(msg));
}
// Private methods to create the websocket
public _connect(url: string): Subject<MessageEvent> {
if (!this._subject) {
this._subject = this._create(url);
}
return this._subject;
}
private _create(url: string): Subject<MessageEvent> {
this._ws = new WebSocket(url);
let observable = Observable.create(
(obs: Observer<MessageEvent>) => {
this._ws.onmessage = obs.next.bind(obs);
this._ws.onerror = obs.error.bind(obs);
this._ws.onclose = obs.complete.bind(obs);
return this._ws.close.bind(this._ws);
}).share();
let observer = {
next: (data: Object) => {
if (this._ws.readyState === WebSocket.OPEN) {
this._ws.send(JSON.stringify(data));
}
}
};
return Subject.create(observer, observable);
}
} // end class
Then in the component I do:
constructor( private wsMachineService: WSMachineService) { ... }
ngOnInit() {
...
this.wsMachineService.connect();
// connexion du web socket
this.wsMachineService.messages.subscribe(
machine => {
console.log(" wsMachineService open and alive", machine);
},
err => {
// This code is never executed
console.log(" wsMachineService closed by server!!", err);
}
);
}
ngOnDestroy() {
//let tmp = this.synoptiqueSocketSubscription.unsubscribe();
this.wsMachineService.messages.unsubscribe();
this.wsMachineService.close()
}
I guess I'm missing something in the _create function because I try to do a catch in the subject of the connect function and it does not work.
Any ideas of how I can know if it is being closed and try to reconnect again?
Thank you
Edit: I think my problem is related to the subject / observables as I do not control them totally. I had an old approach where I could know when the server was dead and it was trying to reconnect each X seconds but unfortunately, I wasn't able to close the connection from the client as I didn't have access to the websocket object. I add the code as well:
public messages: Observable<any>;
private ws: Subject<any>;
private url: string;
public onclose = new Subject();
public connect(urlApiWebSocket: string): Observable<any> {
if (this.messages && this.url === urlApiWebSocket) {
return this.messages;
}
this.url = urlApiWebSocket;
this.ws = Observable.webSocket({
url: urlApiWebSocket,
closeObserver: this.onclose
});
return this.messages = this.ws.retryWhen(errors => errors.delay(10000)).map(msg => msg).share();
}
send(msg: any) {
this.ws.next(JSON.stringify(msg));
}
Let's see if we have any way to combine both solutions.
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/49282265/angular4-websocket-rxjs-reconnect-and-onerror