英文:
Golang Server Sent Events - Does Server Sent Event Handler Continually Call Itself?
问题
我正在学习服务器发送事件(Server Sent Events),我有一个简单的程序,它会递增一个计数器变量并将其推送给客户端。但是我不明白其中的一些问题。有人告诉我数据只会被推送给客户端,而不是由客户端拉取或请求。那么在下面的代码中会发生什么呢?/sse/dashboard 处理程序是每秒钟调用自身吗?因为看起来是这样的。它是如何知道要持续"调用自身"的呢?下面是我的服务器端代码,然后是我的客户端代码:
服务器端:
package main
import (
"fmt"
"log"
"net/http"
)
var counter int
func main() {
http.Handle("/", http.FileServer(http.Dir("client")))
http.Handle("/sse/dashboard", http.HandlerFunc(func(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")
counter++
fmt.Fprintf(w, "data: %v\n\n", counter)
}))
log.Fatal(http.ListenAndServe(":8080", nil))
}
客户端:
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Counter: <span id="counter_val"></span></h1>
<script>
var source = new EventSource("/sse/dashboard");
source.onmessage = function (event) {
var counter = JSON.parse(event.data);
document.getElementById("counter_val").innerHTML = counter;
}
</script>
</body>
</html>
英文:
I'm learning about server sent events and I've a simple program that increments a counter variable and pushes to client. But I don't understand something. I'm told that data is only pushed to the client. Not pulled or requested from client. So what happens in the below code. Does the /sse/dashboard handler call itself every second. Because that's how it would appear. How does it know to continually 'call itself'? Below is my server side code, followed by my client side code:
Server Side:
package main
import (
"fmt"
"log"
"net/http"
)
var counter int
func main() {
http.Handle("/", http.FileServer(http.Dir("client")))
http.Handle("/sse/dashboard", http.HandlerFunc(func(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")
counter++
fmt.Fprintf(w, "data: %v\n\n", counter)
}))
log.Fatal(http.ListenAndServe(":8080", nil))
}
Client Side:
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Counter: <span id="counter_val"></span></h1>
<script>
var source = new EventSource("/sse/dashboard");
source.onmessage = function (event) {
var counter = JSON.parse(event.data);
document.getElementById("counter_val").innerHTML = counter;
}
</script>
</body>
</html>
答案1
得分: 2
处理程序仅在客户端发出对/sse/dashboard的请求时才被调用。处理程序不会自行调用。
客户端的EventSource在服务器关闭事件流后会自动重新连接。服务器在第一条消息后关闭事件流。您会看到一个递增的计数器,因为客户端每一秒或两秒重新连接一次。
使用循环发送递增的计数器事件。当客户端断开连接时,从处理程序返回。将响应写入器缓冲的输出刷新到网络。使用互斥锁来防止counter
上的数据竞争。
var (
mu sync.Mutex
counter int
)
...
http.Handle("/sse/dashboard", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Internal error", 500)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
t := time.NewTicker(time.Minute)
defer t.Stop()
for {
select {
case <-t.C:
mu.Lock()
counter++
c := counter
mu.Unlock()
fmt.Fprintf(w, "data: %v\n\n", c)
flusher.Flush()
case <-r.Context().Done():
return
}
}
}))
英文:
The handler is only invoked when a client issues a request to /sse/dashboard. A handler does not invoke itself.
The client's EventSource automatically reconnects after the server closes the event stream. The server close the event stream after the first message. You see an incrementing counter because the client reconnects every second or two.
Use a loop to send incrementing counter events. Return from the handler when the client disconnects. Flush the output buffered by the response writer to the network. Use a mutex to prevent the data race on counter
.
var (
mu sync.Mutex
counter int
)
...
http.Handle("/sse/dashboard", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Internal error", 500)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
t := time.NewTicker(time.Minute)
defer t.Stop()
for {
select {
case <-t.C:
mu.Lock()
counter++
c := counter
mu.Unlock()
fmt.Fprintf(w, "data: %v\n\n", c)
flusher.Flush()
case <-r.Context().Done():
return
}
}
}))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论