Websocket-sockjs-InvalidStateError:尚未建立连接

时间:2018-10-19 19:41:22

标签: javascript angular websocket stomp sockjs

在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   错误错误:未捕获(承诺):错误: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'})
    )

1 个答案:

答案 0 :(得分:0)

当然-建立连接需要一些时间。 我非常急于发送第一个消息。 因此,在放松1秒钟后,便会发送和接收邮件!