Web邮箱客户端因高邮件速率而崩溃

时间:2018-03-05 15:55:28

标签: javascript websocket

我的javascript websocket客户端在以高速率接收消息时崩溃。我尝试了3个浏览器,它们都崩溃了。首先是Chrome,IE第二,而Edge可以保持更长的时间。

在不到一秒的时间内,消息大约是30条消息。所有大约10-20个字符长(数据部分)。

onmessage是否称为异步?并且它们可以并行运行(下一个onmessage已经在上一个完成之前启动)还是请求放在某种队列中?

我试图"阻止" onMessage无济于事。



var blockWS = false;

function pageLoad() {
  if ('WebSocket' in window) {
    var ws = new WebSocket(((window.location.protocol === 'https:') ? 'wss://' : 'ws://') + window.location.host + '/ws');
    ws.onmessage = function(message) {
      while (blockWS) {
        // wait
      }
      blockWS = true;
      var el = document.getElementById('printer');
      el.innerHTML += message.data;
      el.scrollTop = el.scrollHeight;
      blockWS = false;
    };
  } else {
    // The browser doesn't support WebSocket
    document.getElementById('body').innerHTML = '<h1>Your browser does not support WebSocket.</h1>';
  }
}
&#13;
<html>

<body onload="pageLoad()">
  <div id="body">
    <div id="printer"></div>
  </div>
</body>

</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

执行您想要做的事情的简单(不确定性能)方法是在循环之外使用setInterval()方法,只是在从websockets进来时存储消息数组。以下是您可以执行的一些测试代码:

编辑:我添加了代码的更新部分,以便只有在需要显示新消息时才会插入DOM。

// Your code that is crashing the browser:
/*var blockWS = false;

function pageLoad() {
  if ('WebSocket' in window) {
    var ws = new WebSocket(((window.location.protocol === 'https:') ? 'wss://' : 'ws://') + window.location.host + '/ws');
    ws.onmessage = function(message) {
      while (blockWS) {
        // wait
      }
      blockWS = true;
      var el = document.getElementById('printer');
      el.innerHTML += message.data;
      el.scrollTop = el.scrollHeight;
      blockWS = false;
    };
  } else {
    // The browser doesn't support WebSocket
    document.getElementById('body').innerHTML = '<h1>Your browser does not support WebSocket.</h1>';
  }
}*/

// Using the setInterval method (I used 1s, but you can change that to your preferences):
function pageLoad() {
  const MESSAGE_INSERT_TIME_MS = 1000;
  let messages = [];
  let intervalId = null;
  
  if ('WebSocket' in window) {
    const protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
    const ws = new WebSocket(`${protocol}${window.location.host}/ws`);
    
    ws.onmessage = (message) => {
      messages.push(message);
    };
    
    // At any point inside the "pageLoad()" function, you can use "intervalId.clearInterval()" to stop doing this function.
    intervalId = setInterval(() => {
      const el = document.getElementById('printer');
      
      if (!el.innerHTML === messages.join('')) {
        el.innerHTML = messages;
        el.scrollTop = el.scrollHeight;
      }
    }, MESSAGE_INSERT_TIME_MS);
  }
}