Websocket: Failed to execute 'send' on 'WebSocket': Still in CONNECTING s

逃离我推掉我的手 2022-07-15 13:48 225阅读 0赞

在使用WebSocket时有时会报出这样的错误:

Uncaught InvalidStateError: Failed to execute ‘send’ on ‘WebSocket’: Still in CONNECTING state

这个错误有可能的原因是该WebSocket对象正在发送问题,发送还没结束,然后调用者又调用了send方法接着继续发送,所以still in connecting,解决这个问题的方法是通过判断readyStatus延时发送:

  1. this.send = function (message, callback) {
  2. this.waitForConnection(function () {
  3. ws.send(message);
  4. if (typeof callback !== 'undefined') {
  5. callback();
  6. }
  7. }, 1000);
  8. };
  9. this.waitForConnection = function (callback, interval) {
  10. if (ws.readyState === 1) {
  11. callback();
  12. } else {
  13. var that = this;
  14. // optional: implement backoff for interval here
  15. setTimeout(function () {
  16. that.waitForConnection(callback, interval);
  17. }, interval);
  18. }
  19. };

发表评论

表情:
评论列表 (有 0 条评论,225人围观)

还没有评论,来说两句吧...

相关阅读