如何在打字稿上重新连接(重新订阅)到 websocket

Posted

技术标签:

【中文标题】如何在打字稿上重新连接(重新订阅)到 websocket【英文标题】:How reconnect (resubscribe) to websocket on typescript 【发布时间】:2018-07-21 17:06:34 【问题描述】:

我有一个 Ionic3 应用程序,它在某个视图上连接视图进入并订阅 websocket 可观察/观察者服务:

subscribtion: Subscription;


ionViewDidEnter() 
    this.subscribtion =  this.socket.message.subscribe(msg => 
    let configs = <Configs>msg.data 
    this.inputs = configs.inputs;
  );
  this.socket.message.next(this.enterMessage);

然后,在离开视图时,取消订阅:

ionViewWillLeave() 
  this.socket.message.next(this.quitMessage);
  this.subscribtion.unsubscribe();

但是如果我重新进入视图,它不会重新连接到 websocket。我该怎么做?

这里是socket和websocket.ts:

@Injectable()
export class SocketProvider 

public message: Subject<Message>;

  constructor(private socket: WebsocketProvider, @Inject('server') private server) 
    console.log('Hello SocketProvider Provider');
    let wsAddr = this.server.webSocketUrl();
    this.message = <Subject<Message>>socket
    .connect(wsAddr)
    .map((response: MessageEvent): Message => 
        let data = JSON.parse(response.data);
        return data;
    )
  

  


private subject: Rx.Subject<MessageEvent>;

public connect(url): Rx.Subject<MessageEvent> 
  if (!this.subject) 
    this.subject = this.create(url);
    //console.log('successfully Connnect: ' + url);
  
  return this.subject;


public create(url): Rx.Subject<MessageEvent> 
let ws = new WebSocket(url);

let observable = Rx.Observable.create(
  (obs: Rx.Observer<MessageEvent>) => 
    ws.onmessage = obs.next.bind(obs);
    ws.onerror = obs.error.bind(obs);
    ws.onclose = obs.complete.bind(obs);
    return ws.close.bind(ws);
  
)

let observer = 
  next: (data: Object) => 
    if (ws.readyState === WebSocket.OPEN) 
      ws.send(JSON.stringify(data));
    
  


return Rx.Subject.create(observer, observable);


【问题讨论】:

【参考方案1】:

我找到了解决办法:

我将 socket.ts 中构造函数中的代码移动到我在 IonViewEnter() 中调用的连接函数中并重新初始化 WebSocketProvider 对象:

constructor(private socket: WebsocketProvider, @Inject('server') private server) 
  console.log('Hello SocketProvider Provider');


connect() 
  console.log("try to connect eb socket");
  this.socket = new WebsocketProvider;
  let wsAddr = this.server.webSocketUrl();
  //let wsAddr = 'ws://192.168.0.110:8181';
  this.message = <Subject<Message>>this.socket
  //.connect('wss://echo.websocket.org')
  .connect(wsAddr)
  .map((response: MessageEvent): Message => 
    try 
      let data = JSON.parse(response.data);
      return data;
    catch(e) 
      alert(e);
      console.log("receive invalid JSON message: ");
      console.log(response.data);
    
  )  

【讨论】:

以上是关于如何在打字稿上重新连接(重新订阅)到 websocket的主要内容,如果未能解决你的问题,请参考以下文章

如何在 apollo 客户端中检测订阅(websocket)的断开和重新连接

苗条打字稿上的苗条自定义事件

是否可以仅为打字稿上的特定类型扩展 Array.prototype?

类型“typeof File”离子打字稿上不存在属性“moveFile”

如何在 Socket.IO 中模拟连接失败

vscode没有在vue文件中重新加载打字稿