我的服务器代码在 golangpackage mainimport 中(\'fmt\' \'log\' \'net/http\' \'github.com/rs/cors\')func main() { mux := http.NewServeMux();...
我的服务器代码用 golang 编写
package main
import (
"fmt"
"log"
"net/http"
"github.com/rs/cors"
)
func main() {
mux := http.NewServeMux();
mux.HandleFunc("/sse" , handleSse)
c := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{http.MethodGet, http.MethodPost,
http.MethodDelete , http.MethodPut},
AllowCredentials: true,
})
handler := c.Handler(mux)
log.Fatal(http.ListenAndServe(":6969" , handler))
}
func handleSse(w http.ResponseWriter , r * http.Request){
w.Header().Set("Content-type","text/event-stream")
w.Header().Set("Cache-Control","no-cache")
w.Header().Set("Connection","keep-alive")
f , ok := w.(http.Flusher);
if !ok{
http.Error( w , "SSE not supported" ,
http.StatusBadRequest)
return;
}
fmt.Fprintf(w,"data:%v\n\n","sample data");
f.Flush();
}
客户端代码
<!DOCTYPE html>
<html lang="en">
<head>
<title>SSE</title>
</head>
<body>
SSE running
<script>
const event = new EventSource("http://localhost:6969/sse");
event.onmessage = () =>{
console.log("this dude is slow");
};
</script>
</body>
</html>
我遇到的问题是,在网络选项卡中,新的文本流或响应在 5.4 秒后出现。我希望服务器每 2 秒发送一次响应,我尝试在服务器代码中使用无限 for 循环,如某些教程中所示,但它不起作用
编辑:for 循环处理程序函数
func handleSse(w http.ResponseWriter , r * http.Request){
w.Header().Set("Content-type","text/event-stream")
w.Header().Set("Cache-Control","no-cache")
w.Header().Set("Connection","keep-alive")
w.WriteHeader(http.StatusOK)
f , ok := w.(http.Flusher);
if !ok{
http.Error( w , "SSE not supported , IE6 bruh" ,
http.StatusBadRequest)
return;
}
for i := 0 ; i < 10 ; i++{
fmt.Fprintln(w,"retry : 1000"); //This line also doesnot help
fmt.Fprintf(w,"data :%v\n\n","Sorry");
f.Flush();
//time.Sleep(1 * time.Second) //This line increase delay to 25 secs
}
}