如何通过XMLHttpRequest创build并保存http长连接
让我说:我想创build一个http长连接。
// nodejs代码
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代码
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:无法执行'XMLHttpRequest'发送':对象的状态必须打开。
PS:我想我已经成功创build了一个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) });