小编Zac*_*ack的帖子

在 firebase 函数中实现服务器发送事件功能

我试图在 firebase 函数中实现服务器发送事件功能,在函数执行时它将不断地将数据发送回客户端,而不是在函数完成时发送回数据。我尝试过的所有操作都只是使函数在执行结束时返回任何数据。是否有可能将数据从 firebase 函数流回客户端,或者它是否缓存和缓冲所有内容,直到完成执行?是否有另一种方法可以使用 firebase 函数来以不同的方式执行此功能?

我试图在 firebase 函数中实现服务器发送事件功能,在函数执行时它将不断地将数据发送回客户端,而不是在函数完成时发送回数据。我尝试过的所有操作都只是使函数在执行结束时返回任何数据。

到目前为止,这是我的代码:

函数/index.js:

const functions = require("firebase-functions");
const express = require("express");

const app = express();

app.get("/sse", (request, response) => {
  // Set headers to indicate that the response is an SSE stream
  response.setHeader("Content-Type", "text/event-stream");
  response.setHeader("Cache-Control", "no-cache");
  response.setHeader("Connection", "keep-alive");

  // Send initial message to client
  response.write("data: Connected\n\n");

  // Send data to the client every second
  const intervalId = setInterval(() => {
    const data = { message: "Hello world!" };
    response.write(`data: ${JSON.stringify(data)}\n\n`);
    response.flush(); …
Run Code Online (Sandbox Code Playgroud)

javascript firebase reactjs google-cloud-functions

6
推荐指数
1
解决办法
1184
查看次数