看起来有几个类似的问题,但几天后我找不到合适的答案。我的问题是如何知道服务器是否已关闭websocket以及如何尝试重新连接。我已经看过几个例子,但是当我想要在我改变视图时实现从客户端关闭websocket的功能时,它们都没有正常工作。
然后我发现这个example是我迄今为止看到的最好的一个,并且通过一些小的修改,我能够添加一个非常好的关闭函数。
从客户端关闭websocket不再是问题,但是,我无法知道websocket 何时被服务器关闭以及如何重新连接 。
我的代码与this问题非常相似,但我要求的是另一回事。此外,我在重新使用websocket时遇到了问题,直到我看到他们在我放置的链接中所说的共享功能,因此在我发布的类中,websocket服务和使用websocket服务的服务合并为一个< / p>
我的websocket服务
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
然后在我做的组件中:
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()
}
我想我在_create函数中遗漏了一些东西,因为我尝试在connect函数的主题中做一个catch并且它不起作用。
我是如何知道它是否被关闭并尝试重新连接的想法?
谢谢
编辑: 我认为我的问题与主题/观察者有关,因为我没有完全控制它们。我有一个旧方法,我可以知道服务器什么时候死了,它试图重新连接每个X秒但不幸的是,我无法关闭客户端的连接,因为我无法访问websocket对象。我也添加了代码:
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));
}
让我们看看我们是否有办法将两种解决方案结合起来。
答案 0 :(得分:1)
好吧,我找到了办法。我使用Observable.websocket
的旧方法sr_cat_type_cd
当我使用它时:
@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();
}
看起来我所要做的就是调用函数complete()来告诉服务器客户端已经完成。 我确信有更好的方法,但这是我发现的唯一适合我的方式。
感谢您的帮助。
答案 1 :(得分:0)
您无法知道服务器何时与客户端建立关联。
如您所知,this._ws.onclose = obs.complete.bind(obs);
仅在客户完成“关闭”操作时才会触发。
常见的游戏方式: