首页 > 使用node.js创建一个websocket时,不调用res.end(),客户端无法显示数据

使用node.js创建一个websocket时,不调用res.end(),客户端无法显示数据

用node.js创建一个websocket:

javascriptresponse.writeHead(200,{"Content-Type": "text/event-stream"});
        var timer = setInterval(function(){
            var content = "date:" + new Date().toUTCString() + "\n\n";
            response.write(content);
            console.log("Data got queued in memory (content=" + content + ")");
        },1000)

由于websocket,需要不断发送内容,所以不能使用response.end(),但是不执行这句话,前端的数据就始终在等待状态.请问有什么办法能每次response.write()一点,前端就接受一点,类似于php的@flush()那样...


你这不是websocket吧,只是响应了一个http请求。可以用socket.io建立个websocket连接,定时发送数据到前端页面。https://github.com/Automattic/socket.io

【热门文章】
【热门文章】