Koa SSE "write after end"

Koa SSE "write after end"

几个小时以来,我一直在尝试使用 Koa 实现 SSE 流,但在初始化连接后尝试向我的客户端发送消息时出现以下错误。

Error [ERR_STREAM_WRITE_AFTER_END]: write after end

以下是我设置 SSE 的方法:

客户端:

const source = new EventSource("http://localhost:8080/stream");

this.source.onmessage = (e) => {
  console.log("---- RECEIVED MESSAGE: ", e.data);
};

// Catches errors
this.source.onerror = (e) => {
  console.log("---- ERROR: ", e.data);
};

服务器端(Koa):

// Entry point to our SSE stream
router.get('/stream', ctx => {

  // Set response status, type and headers
  ctx.response.status = 200;
  ctx.response.type = 'text/event-stream';
  ctx.response.set({
    'Cache-Control': 'no-cache',
    Connection: 'keep-alive',
  });

  // Called when another route is reached
  // Should send to the client the following
  ctx.app.on('message', data => {
    ctx.res.write(`event: Test\n`);
    ctx.res.write(`data: This is test data\n\n`);
  });   
});

当我们在收到消息后调用 ctx.res.write 时出现错误。

为什么我的直播结束了,尽管没有明确的动作? 我如何使用 Koa 通过流发送消息?

Koa 完全基于 promise,一切都是中间件。

每个中间件 return 都是一个承诺(或者什么都不是)。中间件链实际上是 'awaited',一旦中间件 returns,Koa 知道响应已完成并将结束流。

要确保 Koa 不会这样做,您必须确保中间件链不会结束。为此,您需要 return 一个仅在您完成流式传输时才解析的承诺。

一个快速演示的技巧是return一个无法解决的承诺:

return new Promise( resolve => { }});