我正在尝试在Firebase函数中实现服务器发送事件功能,使其在函数执行时连续向客户端发送数据,而不是在函数完成时返回数据。但是,我尝试过的所有方法都只会在执行结束时返回数据。是否有可能从Firebase函数向客户端流式传输数据,或者它会缓存和缓冲所有内容直到执行完成?是否有其他方法可以使用Firebase函数执行此功能并以不同的方式完成?
以下是我的代码:
以下是我的代码:
functions/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(); // Send buffered data to client immediately
}, 1000);
// End the response when the client closes the connection
request.on("close", () => {
clearInterval(intervalId);
response.end();
});
});
exports.sseFunction = functions.https.onRequest(app);
然后是我在客户端的函数:
export const sseFunctionStream = async () => {
const eventSource = new EventSource(
"https://us-central1-<project-id>.cloudfunctions.net/sseFunction/sse"
);
eventSource.addEventListener("message", (event) => {
const data = JSON.parse(event.data);
console.log(data);
});
return () => {
eventSource.close();
};
};
我尝试了几种实现方式,但它们都导致同样的结果:事件监听器在函数执行时不会获取任何数据,直到函数完成。一旦完成,它就会获取所有数据。我希望在客户端每秒钟监听事件时,它能像在函数中一样,在控制台记录“Hello World”。