仅仅利用http模块能实现一个最简单的长连接demo么?
先设置不超时,然后每个1s向页面输出一段字符串这种。在一个请求处理过程中,只能调用一次res.end,如果只写res.write的话页面又无法拿到数据。有啥方法能实现么?
12 回复
res没这方法吧,我这边直接报错undefined is not a function:
var http = require('http'),
i = 0;
var server = http.createServer(function(req, res) {
console.log('in createServer');
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.flush('1');
});
server.listen(8888);
嗯…是没有 flush这个, 现在改成 res.flushHeaders() 了
我试了一种
- set
content-type: text/html; charset=utf-8 res.flushHeaders();res.write即可以及时显示了
const http = require('http');
http.createServer(function(req, res) {
var i = 1;
var timer;
res.statusCode = 200;
// text/plain 似乎有bug, 具体不太清楚
res.setHeader('Content-Type', 'text/html');
res.setHeader('Transfer-Encoding', 'chunked');
res.write('<!doctype html><html><head></head><body>');
timer = setInterval(function() {
res.write(i + '<br />');
if (++i > 10) {
res.end('</body>');
clearInterval(timer);
}
}, 1000);
}).listen(8888, function() {
console.log('http://localhost:8888');
});
@William17 你这样不对吧,你是把字符串全部生成然后返回给前端的,这应该不是楼主想要的。 Flask框架是有这样的方法的:http://stackoverflow.com/questions/13386681/streaming-data-with-python-and-flask