簡體   English   中英

res.write() 不會立即結束事件

[英]res.write() not end event immediately

這段代碼從今天起就不能正常工作,在今天之前,這在響應上運行良好,所有 response.write() 都在事件流上執行,但現在問題是 response.write() 執行 api 響應結束。 以及一次列出的所有事件。

const express = require('express');

const app = express();
app.use(express.static('public'));

app.get('/countdown', function(req, res) {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    Connection: 'keep-alive',
    'Access-Control-Allow-Origin': '*'
  });
  countdown(res, 1, 10);
});

function countdown(res, id, count) {
  res.write(`id: ${id}\n`);
  res.write('event: count\n');
  res.write(`data: ${JSON.stringify({ count: count })}\n\n`);
  if (count) setTimeout(() => countdown(res, id + 1, count - 1), 1000);
  else res.end();
}

app.listen(3000, () => console.log('SSE app listening on port 3000!'));

並在您的首頁使用 EventSource:

<script>
  var source = new EventSource('http://localhost:3000/countdown');
  source.onmessage = function(event) {
    console.log(event);
  };
</script>

聽起來這是一個“周期性”問題。 您可以創建的連接數量是有限制的,特別是當/如果協議是 HTTP 時(請參閱EventSource 介紹中的警告框)。

這可以通過確保每次關閉/重新加載網頁時關閉連接來緩解。 根據我的經驗,瀏覽器最終會清理未使用的連接,但我不知道什么時候。

var source = new EventSource('http://localhost:3000/countdown');

window.addEventListener('beforeunload', e => {
  // if the connection is not already closed, close it
  if(source.readyState != source.CLOSED){
    source.close();
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM