0

我一直试图弄清楚这个几个小时......

我使用了各种解释它的教程,将代码复制到我的代码中,但它不起作用。没有错误信息,什么都没有。

这是我正在做的事情:

客户:

<script>
startStream()
function startStream()
{
    source = new EventSource("/stream")
    if(typeof(EventSource) !== "undefined") {
        console.log("streams are supported")

        source.addEventListener('message', function(e) {
          console.log(e.data);
        }, false);

        source.onerror = function(event) {
            source.close();
        }
    } else {
        console.log("no stream support")
    }
}
</script>

服务器:

http = require('http')
fs = require('fs')

var server = http.createServer(function(request, response)
{
    //understand the request
    var path = request.url
    if(path == "/")
        path = "/index.html"
    console.log("request for "+path)
    if (path.indexOf("stream") != -1)
    {
        console.log("- client requesting stream")
        response.writeHead(200, {"Content-Type":"text/event-stream", "Cache-Control":"no-cache", "Connection":"keep-alive"})
        response.write('\n')

        var interval = setInterval(function() {
            console.log("- sending stream data")
            response.write("data: message")
            response.write('\n')
        }, 1000);

        request.connection.addListener("close", function () {
              clearInterval(interval);
        }, false);
        return 0
    }

    var html = fs.readFileSync("index.html","utf-8").toString();
    response.writeHead(200, {"Content-Type": "text/html"})
    response.write(html)
    response.end()
})

//wait for requests
var port = 5001
server.listen(port)
console.log("listening on port "+port+"...")

在stackoverflow上,有人也遇到了流问题,然后建议必须插入response.end()。它对那个人有用。我只是收到一个错误,当我这样做时连接关闭后我无法写入。这就像魔术(“错误:结束后写”)

服务器输出:

request for /stream
- client requesting stream
- sending stream data
- sending stream data
- sending stream data
- sending stream data
- sending stream data

客户端输出:

streams are supported

客户端响应标头:

HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive
Date: Sun, 23 Apr 2017 09:48:04 GMT
Transfer-Encoding: chunked

客户端请求标头:

GET /stream HTTP/1.1
Host: localhost:5000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0
Accept: text/event-stream
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost:5000/
Cookie: 0f62446157da624a2edb8a2b53d86dc1=de-DE
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

除此之外,网络检查器中没有任何其他内容

4

1 回答 1

0

天哪,在发布问题后不久

每条消息必须在末尾包含两个\n

response.write("data: message")
response.write('\n\n')
于 2017-04-23T10:12:44.853 回答