使用node.js创建一个websocket时,不调用res.end(),客户端无法显示数据
伊谢尔伦
伊谢尔伦 2017-04-17 11:33:31
0
2
643

用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()那样...

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(2)
巴扎黑

This is not a websocket, it is just responding to an http request. You can use socket.io to establish a websocket connection and send data to the front-end page regularly. https://github.com/Automattic/socket.io

左手右手慢动作

Obviously your code is not websocket, but SSE server code.
The reason why the code failed was a typo. . . .

var content = "date:" + new Date().toUTCString() + "\n\n";

should be:

var content = "data:" + new Date().toUTCString() + "\n\n";
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template