|
@@ -17,6 +17,45 @@ type ServerSentRouter struct {
|
|
*xweb.Action
|
|
*xweb.Action
|
|
events xweb.Mapper `xweb:"/sse/events"`
|
|
events xweb.Mapper `xweb:"/sse/events"`
|
|
send xweb.Mapper `xweb:"/sse/send"`
|
|
send xweb.Mapper `xweb:"/sse/send"`
|
|
|
|
+ notify xweb.Mapper `xweb:"/sse/notify"`
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+func (s *ServerSentRouter) Notify() {
|
|
|
|
+ defer common.Catch()
|
|
|
|
+ s.ResponseWriter.Header().Set("Content-Type", "text/event-stream")
|
|
|
|
+ s.ResponseWriter.Header().Set("Cache-Control", "no-cache")
|
|
|
|
+ s.ResponseWriter.Header().Set("Connection", "keep-alive")
|
|
|
|
+ s.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
|
|
|
|
+
|
|
|
|
+ sessVal := s.Session().GetMultiple()
|
|
|
|
+ userId := common.ObjToString(sessVal["userId"])
|
|
|
|
+ if userId != "" {
|
|
|
|
+ // 创建用户专属的消息通道
|
|
|
|
+ messageChan := make(chan string)
|
|
|
|
+ // 注册当前连接
|
|
|
|
+ util.SseClientsMu.Lock()
|
|
|
|
+ util.SseClients[userId] = messageChan
|
|
|
|
+ util.SseClientsMu.Unlock()
|
|
|
|
+
|
|
|
|
+ // 客户端断开时清理资源
|
|
|
|
+ defer func() {
|
|
|
|
+ util.SseClientsMu.Lock()
|
|
|
|
+ delete(util.SseClients, userId)
|
|
|
|
+ close(messageChan)
|
|
|
|
+ util.SseClientsMu.Unlock()
|
|
|
|
+ }()
|
|
|
|
+ // 监听消息通道并发送给客户端
|
|
|
|
+ flusher := s.ResponseWriter.(http.Flusher)
|
|
|
|
+ for {
|
|
|
|
+ select {
|
|
|
|
+ case msg := <-messageChan:
|
|
|
|
+ fmt.Fprintf(s.ResponseWriter, "data: %s\n\n", msg)
|
|
|
|
+ flusher.Flush()
|
|
|
|
+ case <-s.Request.Context().Done():
|
|
|
|
+ return // 客户端断开连接
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+ }
|
|
}
|
|
}
|
|
|
|
|
|
func (s *ServerSentRouter) Send() {
|
|
func (s *ServerSentRouter) Send() {
|