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 关注
- 128 浏览
添加回答
举报