Websocket 如果web套接字已关闭,请重新连接它
我的web套接字连接代码:Websocket 如果web套接字已关闭,请重新连接它,websocket,angular7,Websocket,Angular7,我的web套接字连接代码: public connect(): Subject<MessageEvent> { if (!this.subject) { this.subject = this.create(this.url); } this.ws.onerror = () => { this.close(); let refresh = setInterval(() => { this.s
public connect(): Subject<MessageEvent> {
if (!this.subject) {
this.subject = this.create(this.url);
}
this.ws.onerror = () => {
this.close();
let refresh = setInterval(() => {
this.subject = null;
this.connect();
this.ws.onopen = () => {
clearInterval(refresh)
}
}, 5000);
}
return this.subject;
}
private create(url: string){
this.ws = new WebSocket(url);
const observable = Observable.create((obs: Subject<MessageEvent>) => {
this.ws.onmessage = obs.next.bind(obs);
this.ws.onerror = obs.error.bind(obs);
this.ws.onclose = obs.complete.bind(obs);
this.ws.onclose = function () {
console.log("trying to reconnect");
this.connect();
}
return this.ws.close.bind(this.ws);
});
const observer = {
next: (data: any) => {
if (this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(data));
}
}
};
return Subject.create(observer, observable);
}
public connect():主题{
如果(!this.subject){
this.subject=this.create(this.url);
}
this.ws.onerror=()=>{
这个。关闭();
let refresh=setInterval(()=>{
this.subject=null;
这个.connect();
this.ws.onopen=()=>{
清除间隔(刷新)
}
}, 5000);
}
返回此.subject;
}
私有创建(url:string){
this.ws=新的WebSocket(url);
const observable=observable.create((obs:Subject)=>{
this.ws.onmessage=obs.next.bind(obs);
this.ws.onerror=obs.error.bind(obs);
this.ws.onclose=obs.complete.bind(obs);
this.ws.onclose=函数(){
日志(“尝试重新连接”);
这个.connect();
}
返回this.ws.close.bind(this.ws);
});
常量观察者={
下一步:(数据:任意)=>{
if(this.ws.readyState===WebSocket.OPEN){
this.ws.send(JSON.stringify(data));
}
}
};
返回主题。创建(观察者、可观察者);
}
如果连接关闭,我想重新连接web套接字。当我停止web套接字时,函数被触发。但是没有再次连接。我看到错误“this.connect不是一个函数”。如何使用角度递归函数?如果您不知道如何根据执行上下文更改
this
引用,请不要在其内部使用this
关键字创建回调,改用箭头功能
要使其重新连接,请更改此选项
this.ws.onclose = function () {
console.log("trying to reconnect");
this.connect();
}
对此
this.ws.onclose = () => {
console.log("trying to reconnect");
this.subject = null;
this.connect();
}
你能不能也更新一下如何每X秒调用这个函数?你能详细说明一下吗?