【问题标题】:Server-sent events with node.js http2 module - how should I use it with stream / pushStream?使用 node.js http2 模块的服务器发送事件 - 我应该如何将它与流 / pushStream 一起使用?
【发布时间】:2019-02-04 18:54:51
【问题描述】:

我正在尝试实现每 500 毫秒发送大量数据(对象,而不是文件)的服务器。 经过一番阅读,服务器通过 http2 发送事件似乎是最快的选择(由于 http2 是二进制协议,SSE 减少了流量开销)

在 http/1.1 上与SSE 玩了一会儿之后 我一直在尝试在 http2 上做同样的事情。我尝试使用streampushStream 这样做,但没有成功。但是,使用与 http/1.1 相同的方式似乎可行。

我的问题是 - 为什么使用流的服务器 1(见下文)不起作用,而服务器 2 似乎工作正常?工作节点流时我错过了什么吗?

我正在使用节点 v10.9.0 和 chrome 68.0.3440.106

我已经阅读了以下问题和帖子,但仍然无法解决这个问题:

服务器 1 - 带有流的 http2(不工作 - 客户端没有收到事件。chrome 将请求描述为未完成的请求):

const fs = require('fs');
const http2 = require('http2');

const HTTPSoptions = {
    key: fs.readFileSync('./cert/selfsigned.key'),
    cert: fs.readFileSync('./cert/selfsigned.crt'),
};
const template = `
<!DOCTYPE html> 
<html>
<body>
    <script type="text/javascript">
        const  source = new EventSource('/sse/');
        source.onmessage = function(e) { 
            document.body.innerHTML += e.data + '<br>';
        };
    </script>
</body>
</html>
`;


const server = http2.createSecureServer(HTTPSoptions);

server.on('stream', (stream, headers, flags) => {
    if (stream.url === 'sse/') {
        console.log(stream.respond);
        stream.respond({
            ':status': 200,
            'content-type': 'text/event-stream'
        });
        setInterval(() => stream ? res.write(`data: ${Math.random()}\n\n`) : '', 200);
    }
});

server.on('request', (req, res) => {
    if(req.url === '/') {
        res.end(template);
    }
});



server.listen(3001);

服务器 2 - 带有流的 http2(工作正常):

const fs = require('fs');
const http2 = require('http2');

const HTTPSoptions = {
    key: fs.readFileSync('./cert/selfsigned.key'),
    cert: fs.readFileSync('./cert/selfsigned.crt'),
};
const template = `
<!DOCTYPE html> 
<html>
<body>
    <script type="text/javascript">
        const  source = new EventSource('/sse/');
        source.onmessage = function(e) { 
            document.body.innerHTML += e.data + '<br>';
        };
    </script>
</body>
</html>
`;


const server = http2.createSecureServer(HTTPSoptions);

server.on('request', (req, res) => {
    req.socket.setKeepAlive(true);

    if(req.url === '/sse/') {

        res.writeHead(200, {
            'Content-Type': 'text/event-stream', // <- Important headers
            'Cache-Control': 'no-cache'
        });
        res.write('\n');

        setInterval(() => res.write(`data: ${Math.random()}\n\n`), 200);
    } else {
        res.end(template);
    }
});

server.listen(3001);

【问题讨论】:

    标签: node.js stream server-sent-events http2


    【解决方案1】:

    要获取 http2 流的请求路径,您必须查看 :path 标头 (docs):

    if (headers[':path'] === '/sse/') {
    

    您还尝试使用res.write,而res 应该是stream

    这是一个基于“服务器 1”实现的工作处理函数:

    server.on('stream', (stream, headers, flags) => {
        if (headers[':path'] === '/sse/') {
            stream.respond({
                ':status': 200,
                'content-type': 'text/event-stream'
            });
            setInterval(() => stream.write(`data: ${Math.random()}\n\n`), 200);
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2017-01-26
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-04
      • 1970-01-01
      相关资源
      最近更新 更多