gpt4 book ai didi

go - 服务器发送事件意外行为

转载 作者:行者123 更新时间:2023-12-01 22:21:43 34 4
gpt4 key购买 nike

我正在尝试在我的 Golang 服务器和 VueJS 之间设置一个基本流。我关注了 StackOverflow 上的另一个帖子开始。但是,由于某些奇怪的原因,当我在 chrome 中检查控制台时,输出会不断重复(0、1、2、3、4 -short stop- 0、1、2、3、4 -short stop- 等)。
这是我的代码
main.go

  package main

import (
"io"
"time"

"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
)

func main() {
r := gin.Default()
r.GET("/stream", func(c *gin.Context) {
chanStream := make(chan int, 2)
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 {
c.SSEvent("message", msg)
return true
}
return false
})
})
r.StaticFile("/", "./public.html")
r.Use(static.Serve("/", static.LocalFile("./public.html", true)))
r.Run()
}
公共(public).html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
var stream = new EventSource("/stream");
stream.addEventListener("message", function(e){
console.log(e.data);
});
</script>
</body>
</html>
我是 SSE 和 Vue 的新手,但我认为客户端等待来自服务器的响应。我的期望是,一旦 Gin 流结束,客户端就会一直等待并且在我执行 EventSource.close() 之前什么都不做。输出似乎服务器正常发送响应,但一旦流结束客户端继续发出请求?我不知道。有人可以指出我做错了什么吗?谢谢

最佳答案

你没有错,其实。这是 EventSource 的预期功能api,它总是触发调用,除非它明确停止。查看EventSource API

The EventSource interface is web content's interface to server-sentevents. An EventSource instance opens a persistent connection to anHTTP server, which sends events in text/event-stream format. Theconnection remains open until closed by calling 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
})
public.html
    stream.addEventListener("message", function(e){
if (e.data === "STOPPED") {
console.log("STOP");
stream.close();
} else {
console.log(e.data);
}
});

关于go - 服务器发送事件意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63078034/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com