我正在用SSE编写测试应用程序,但我的问题是 ReadTimeout和WriteTimeout正在每隔10秒关闭客户端连接,因此主页面正在丢失数据。Http服务器读写超时和服务器端事件
我该如何管理这个问题,一起服务SSE和网页,而没有goroutines泄漏风险和SSE工作?
服务器:
server := &http.Server{Addr: addr,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
Handler: s.mainHandler(),
}
处理程序:
func sseHandler(w http.ResponseWriter, r *http.Requests) {
f, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming not supported!", http.StatusInternalServerError)
log.Println("Streaming not supported")
return
}
messageChannel := make(chan string)
hub.addClient <- messageChannel
notify := w.(http.CloseNotifier).CloseNotify()
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
for i := 0; i < 1440; {
select {
case msg := <-messageChannel:
jsonData, _ := json.Marshal(msg)
str := string(jsonData)
fmt.Fprintf(w, "data: {\"str\": %s, \"time\": \"%v\"}\n\n", str, time.Now())
f.Flush()
case <-time.After(time.Second * 60):
fmt.Fprintf(w, "data: {\"str\": \"No Data\"}\n\n")
f.Flush()
i++
case <-notify:
f.Flush()
i = 1440
hub.removeClient <- messageChannel
}
}
}
为什么不增加/禁用超时?你需要每个处理程序单独的超时? – tomasz 2014-11-24 14:07:46
@tomasz可能很棒有一个不同的超时处理程序,我不知道是否有可能,也许有类似的情况下,我的一些最佳做法,我真的不知道它呢... – Mmeyer 2014-11-24 15:04:03