如何通过XMLHttpRequest创建和保持http长连接

时间:2016-07-19 05:56:48

标签: javascript node.js http xmlhttprequest

让我说:我想创建一个http长连接。

// nodejs code

router.get('/random', function (req, res, next) {
res.writeHead(200, {
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
    "Connection": "keep-alive"
});

res.write("blabla\n");
});

// js code

var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
      console.log(xhr.responseText);
    }
    if (xhr.readyState == 3) {
      console.log('receive part of data' + xhr.responseText);
      setTimeout(function () {
        // ???????
        // How to send heartbeat here?
        // ???????
      }, 2000)
    }
  }

  xhr.open('get', '/random', true);
  xhr.send(null);

我试过的是:

setTimeout(function () {
         xhr.send(null);
      }, 2000)

但是它会抛出错误:" Uncaught InvalidStateError:无法执行'发送' on' XMLHttpRequest':对象的状态必须打开。"

PS:我认为我已成功创建了一个http长连接,因为我可以不断发送数据。例如。

router.get('/random', function (req, res, next) {
    res.writeHead(200, {
        "Content-Type": "text/event-stream",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive"
    });

    setInterval(function () {
        res.write("blabla\n");
    },1000)

});

0 个答案:

没有答案