【问题标题】:ensuring STOMP socket connection is established before subscribing确保在订阅之前建立 STOMP 套接字连接
【发布时间】:2018-02-15 00:44:51
【问题描述】:

在我的 Angular 2 项目中,我使用 ng2-stomp-service 建立到服务器的套接字连接。

大多数情况下它工作正常,但有时我在尝试订阅套接字时收到此错误,说我的连接尚未建立:

Error: Uncaught (in promise): Error: InvalidStateError: The connection has not been established yet Error: InvalidStateError: The connection has not been established yet
    at SockJS.send (main.js:158)
    at Client._transmit (stomp.js:159)
    at Client.subscribe (stomp.js:379)
    at StompService.subscribe (stomp.service.ts:132)
    at slide-manager.service.ts:129
    at ZoneDelegate.invoke (zone.js:391)
    at Object.onInvoke (core.es5.js:3933)
    at ZoneDelegate.invoke (zone.js:390)
    at Zone.run (zone.js:141)
    at zone.js:818
    at SockJS.send (main.js:158)
    at Client._transmit (stomp.js:159)
    at Client.subscribe (stomp.js:379)
    at StompService.subscribe (stomp.service.ts:132)
    at slide-manager.service.ts:129
    at ZoneDelegate.invoke (zone.js:391)
    at Object.onInvoke (core.es5.js:3933)
    at ZoneDelegate.invoke (zone.js:390)
    at Zone.run (zone.js:141)
    at zone.js:818
    at resolvePromise (zone.js:770)
    at zone.js:821
    at ZoneDelegate.invokeTask (zone.js:424)
    at Object.onInvokeTask (core.es5.js:3924)
    at ZoneDelegate.invokeTask (zone.js:423)
    at Zone.runTask (zone.js:191)
    at drainMicroTaskQueue (zone.js:584)
    at WebSocket.ZoneTask.invoke (zone.js:490)

这个堆栈跟踪中属于我的部分是 slide-manager.service.ts:129。该代码位于此代码的 stomp.subscribe 行:

this.socketConfig = {
      host: 'http://' + getHost() + '/app-ws',
      debug: true,
      queue: {'init': false}
    };   

 this.stomp.configure(this.socketConfig);
 this.stomp.startConnect().then((frame) => {
 this.stomp.done('init');
 this.connected = true;
 this.spectraSubscription = this.stomp.subscribe('/topic/spectra', (spectra) => {
     if (spectra && (!this.theChart || hostElement.childElementCount === 0) && !this.refreshFlag) {
         this.makeChart(spectra.points, hostElement);
         this.refreshFlag = true;
     } else if (spectra && (this.theChart || hostElement.childElementCount > 0) || this.refreshFlag) {
         this.theChart.collectionView.sourceCollection = spectra.points;
         this.theChart.collectionView.refresh();
     }
  });

在尝试执行 .subscribe() 之前,如何确保确实建立了连接?我想把它放在 .then() 块中就可以了,因为这应该只在连接的承诺解决后执行,但显然即使没有连接存在(根据错误)它仍然会被触发。

或者还有更多我想念的东西?

【问题讨论】:

    标签: angular websocket stomp


    【解决方案1】:

    我能够通过检查 stomp 客户端的内置“状态”属性来解决此问题:

    if (this.stomp.status === 'CONNECTED') {
        // do stuff that requires a connection, like establish subscriptions
    }
    

    【讨论】:

    • 连接不存在怎么办?您是否只是忽略了需要采取的必要行动?
    • 说实话,因为这是 3 年前,我真的不记得程序是如何处理这种情况的。我想它不会以“已连接”的形式出现,因此我们要么必须等待,要么尝试重新建立连接。也许在 ELSE 语句中。抱歉,我没有更多详细信息,因为我无法再访问此代码。
    猜你喜欢
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 2013-09-07
    • 1970-01-01
    相关资源
    最近更新 更多