Websocket - sockjs - InvalidStateError: The connection has not been established yet

Websocket - sockjs - InvalidStateError: The connection has not been established yet

在 Javascript 中使用 stomp.js 和 sockjs 时,我可以很好地连接 Spring 引导后端。

在 Angular5 中使用 stompjs 和 sockjs 时,我不断收到这些错误:

InvalidStateError: 连接尚未建立

有解决办法吗?仅添加 sockjs.min.js、 并没有帮助。

详细日志为:

Setting up connection/1 main.3388a5e3a20e64e3bdb8.bundle.js:1 Setting up connection/2 main.3388a5e3a20e64e3bdb8.bundle.js:1 Going to subscribe ... main.3388a5e3a20e64e3bdb8.bundle.js:1 Opening Web Socket... main.3388a5e3a20e64e3bdb8.bundle.js:1 >>> SEND destination:/app/chat.addUser content-length:29

{"sender":"me","type":"JOIN"} main.3388a5e3a20e64e3bdb8.bundle.js:1 ERROR Error: Uncaught (in promise): Error: InvalidStateError: The connection has not been established yet Error: InvalidStateError: The connection has not been established yet at r.send (scripts.d6f701ecf84f24372966.bundle.js:1)

我在 Angular 中的代码(翻译自 Javascript)是:

 let ws = new SockJS(this.serverUrl);
    this.stompClient = Stomp.over(ws);
    let that = this;
    console.log('Setting up connection/2');
    console.log('Going to subscribe ... ');
    this.stompClient.connect({}, function (frame) {
      console.log('Going to subscribe ... ');
      that.stompClient.subscribe('/topic/public', (payload) => {
          console.log('Subscribe: Incoming message: ' + payload.body);
          if (payload.body) {
            let message = JSON.parse(payload.body);
            if (message.sender === 'MyBot') {
              this.createAndAddChat('you', message.content);
            } else {
              this.createAndAddChat('me', message.content);
            }
            console.log('New message arrived: ' + payload.body);
          }
        },
        error => {
          console.log( 'Subscribe: error: ' + error)
        },
        () => {
         console.log( 'Subscribe, On complete')
        });
    });
    this.stompClient.send("/app/chat.addUser", {},
      JSON.stringify({sender: 'me', type: 'JOIN'})
    )

发送方法现在在启动(!)异步获取连接调用后直接调用。那是错误的。

有2种解决方案:

  • 好:将发送调用放在获取连接的异步主体中。所以建立连接后,调用send方法。
  • 不理想:等待一段时间以完成异步获取连接。
    stompClient.connect({}, function (frame) {
        console.log('Connected: ' + frame);
        setTimeout(function() {
           stompClient.subscribe("/topic/mytopic/", function (message) {
              showDeviceConnection(deviceIds[i], message.body);
           });
        }, 500);});