仅仅利用http模块能实现一个最简单的长连接demo么?
发布于 8 年前 作者 hwoarangzk 5121 次浏览 来自 问答

先设置不超时,然后每个1s向页面输出一段字符串这种。在一个请求处理过程中,只能调用一次res.end,如果只写res.write的话页面又无法拿到数据。有啥方法能实现么?

12 回复

你是怎么读的?AJAX是不行的要全部完成后才能取到数据,write 这样子发送数据只能用 iframe

楼上+1, 要么本页面,要么在iframe里 Transfer-Encoding: chunked

就是说,仅仅http是不行的了?要想实现我说的demo,socket.io比较好哇?

res没这方法吧,我这边直接报错undefined is not a function: <pre> 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); </pre>

Web socket

来自酷炫的 CNodeMD

嗯…是没有 flush这个, 现在改成 res.flushHeaders() 了

我试了一种

  1. set content-type: text/html; charset=utf-8
  2. res.flushHeaders();
  3. res.write 即可以及时显示了

@hwoarangzk

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

@wangyangkobe 请问你试过我的代码了吗? 我代码是每秒向页面res.write一次

回到顶部