search

Home  >  Q&A  >  body text

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

伊谢尔伦伊谢尔伦2785 days ago625

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 11:35:31

    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

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 11:35:31

    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";

    reply
    0
  • Cancelreply