SSE 连接未建立

SSE connection not established

我已经用 fastify 实现了 Server-Sent 事件。

客户代码:

      const url = `${server}/sse/events`;

      const connection = new EventSource(url);
      connection.onopen = () => {
        console.log('The connection has been established.');
      };

      connection.onerror = (error: any) => {
        console.log('Connection error', error);
        connection.close();
      };

服务器代码(路由/sse/events的控制器):

const establishSSEConnection = async function (request, reply) {

    // some application logic

    let headers = {
        'Content-Type': 'text/event-stream',
        Connection: 'keep-alive',
        'Cache-Control': 'no-cache',
        'Access-Control-Allow-Origin': '*',
    };
    reply.raw.writeHead(200, headers);
    reply.raw.flushHeaders();
    headers = null;

    reply.sent = true;
    request.socket.on('close', () => {
        console.log('SSE connection closed');
    });
};

因此,当我在本地使用 docker 进行测试时,一切似乎都很好并且 The connection has been established. 被打印出来了。 但是,当我将它部署到 kubernetes 时,永远不会打印日志,并且在一段时间后记录 SSEconnection closed

所以问题是为什么这在 docker 而不是 kubernetes 中有效?有没有人遇到过这个问题?任何帮助将不胜感激。

谢谢!

GET 连接请求在浏览器中似乎处于挂起状态。 我在 establishSSEConnection 处理程序中添加了 reply.raw.write('OK\n\n');,它起作用了!