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

w3nuxt5m  于 2023-06-23  发布在  其他
关注(0)|答案(3)|浏览(204)

当在JavaScript中使用stomp.js和sockjs时,我可以很好地连接Sping Boot 后端。
在Angular 5中使用stompjs和sockjs时,我不断得到这些错误:
InvalidStateError:尚未建立连接
是否有变通方案?只是添加sockjs.min.js,as mentioned in this post,并没有帮助。
详细日志为:
正在设置连接/1 main.3388a5e3a20e64e3bdb8.bundle.js:1正在设置连接/2 main.3388a5e3a20e64e3bdb8.bundle.js:1正在订阅... main.3388a5e3a20e64e3bdb8.bundle.js:1 Opening Web Socket... main.3388a5e3a20e64e3bdb8.bundle.js:1 >>>发送目的地:/app/chat. add用户内容长度: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'})
    )
iyfamqjs

iyfamqjs1#

send方法现在在启动(!)异步get-connection调用。那是不对的
有两种解决方案:

  • 好:将send调用放在get-connection的async-body中。因此,在建立连接之后,调用send方法。
  • 非最佳:等待一段时间以完成异步获取连接。
0ejtzxu1

0ejtzxu12#

stompClient.connect({}, function (frame) {
        console.log('Connected: ' + frame);
        setTimeout(function() {
           stompClient.subscribe("/topic/mytopic/", function (message) {
              showDeviceConnection(deviceIds[i], message.body);
           });
        }, 500);});
gcxthw6b

gcxthw6b3#

在订阅Sping Boot 主题之前,您应该确保已经建立了连接。使用useState在onConnect()中设置SockJs中的Topics数组。
以下是我解决这个问题的方法:

const [topics, setTopics] = useState([]);

const onConnected = () => {
    //console.log("Connected!!");
    setTopics(['/topic/message']);
}

const onMessageReceived = (data) => {
    console.log(data);
}

return (
   <SockJsClient
        url='http://localhost:8080/ws-message'
        topics={topics}
        onConnect={onConnected}
        onMessage={data=> onMessageReceived(data)}
        debug={true}
   />
)

希望这能回答问题

相关问题