1 回答

TA貢獻1853條經驗 獲得超9個贊
你沒有錯,其實。這是 api 的預期功能EventSource,它總是觸發調用,除非它明確停止。檢查事件源 API
EventSource 接口是 Web 內容與服務器發送事件的接口。EventSource 實例打開與 HTTP 服務器的持久連接,該服務器以文本/事件流格式發送事件。連接保持打開狀態,直到通過調用 EventSource.close() 關閉。
因此,您需要在服務器完成發送數據時進行更新,并讓客戶端知道流是否已停止。這是您的代碼中的示例:
main.go
go func() {
defer close(chanStream)
for i := 0; i < 5; i++ {
chanStream <- i
time.Sleep(time.Second * 1)
}
}()
c.Stream(func(w io.Writer) bool {
if msg, ok := <-chanStream; ok {
if msg < 4 {
c.SSEvent("message", msg)
} else {
c.SSEvent("message", "STOPPED")
}
return true
}
return false
})
公共.html
stream.addEventListener("message", function(e){
if (e.data === "STOPPED") {
console.log("STOP");
stream.close();
} else {
console.log(e.data);
}
});
- 1 回答
- 0 關注
- 127 瀏覽
添加回答
舉報