【问题标题】:Websocket - sockjs - InvalidStateError: The connection has not been established yetWebsocket - sockjs - InvalidStateError:连接尚未建立
【发布时间】:2018-10-19 19:41:21
【问题描述】:

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

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

InvalidStateError: 连接尚未建立

有解决方法吗?只是添加 sockjs.min.js,as mentioned in this post,并没有帮助。

详细日志为:

设置连接/1 main.3388a5e3a20e64e3bdb8.bundle.js:1 设置 up connection/2 main.3388a5e3a20e64e3bdb8.bundle.js:1 去 订阅 ... main.3388a5e3a20e64e3bdb8.bundle.js:1 打开网页 套接字... main.3388a5e3a20e64e3bdb8.bundle.js:1 >>> 发送 目的地:/app/chat.addUser 内容长度:29

{"sender":"me","type":"JOIN"} main.3388a5e3a20e64e3bdb8.bundle.js:1 ERROR 错误:未捕获(在承诺中):错误:InvalidStateError: 连接尚未建立错误:InvalidStateError: 连接尚未建立 在 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'})
    )

【问题讨论】:

    标签: javascript angular websocket stomp sockjs


    【解决方案1】:

    现在在启动(!)异步 get-connection 调用之后直接调用 send 方法。那是错误的。

    有两种解决方案:

    • 好:将发送调用放在 get-connection 的 async-body 中。所以在建立连接后,调用 send 方法。
    • 不是最佳选择:等待一段时间以完成异步获取连接。

    【讨论】:

    • 究竟是什么意思?有人能告诉我如何解决吗?
    • 错误是:连接尚未建立。回顾2年前的解决方案,看到一开始是调用了async get-connection方法。不等它完成,我直接用 send 方法开始了。这是不正确的。选项 1:[1] 为连接留出时间或更好 [2] 在连接完成时调用 send 方法。
    猜你喜欢
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    相关资源
    最近更新 更多