互联网连接断开后,Websocket重新连接问题

时间:2019-08-22 14:47:16

标签: typescript sockets websocket angular7 rxjs6

我正在使用websocket并面临这样的问题,即重新连接后(互联网连接断开后),如果我将数据从一页传递到另一页却没有显示。我正在使用以下代码:

public create(url): Rx.Subject<MessageEvent> {
 this.ws = new WebSocket(url);
 const observable = Rx.Observable.create(
(obs: Rx.Observer<MessageEvent>) => {
this.ws.onopen = function () {
   setInterval(this.ping, 5000);
 };
this.ws.onmessage = obs.next.bind(obs);
   this.ws.onmessage = function(evt){

    obs.next.bind.data);
var msg = evt.data;
if (msg == '__pong__') {
     this.pong();
     return;
};
};
this.ws.onerror = obs.error.bind(obs);
this.ws.onclose = obs.error.bind(obs);
return  this.ws.close.bind( this.ws);
});
 const observer = {
   next: (data: Object) => {
  console.log("event data",data)


  if ( this.ws.readyState === WebSocket.OPEN) {
  this.ws.send(JSON.stringify(data));
  }
},
complete: () => {
  //alert('reconnect');
  this.create(url);
},
error: () => {
  //alert('reconnect');
  this.create(url);
}
 };
    return Rx.Subject.create(observer, observable);
   }


 public  ping() {
   this.ws.send('__ping__');
   let tm = setTimeout(function () {

    }, 5000);
  }
   public  pong() {
   clearTimeout(this.tm);
   }

如果您还有其他建议,例如几分钟后失去互联网连接,然后又恢复,并且websocket自动连接,那么数据应该在不同的页面上实时显示,请告诉我。

非常感谢advacne!

0 个答案:

没有答案