wangshan 3 months ago
parent
commit
faf00ef933
1 changed files with 9 additions and 2 deletions
  1. 9 2
      services/sse/sse.go

+ 9 - 2
services/sse/sse.go

@@ -31,8 +31,11 @@ func (s *ServerSentRouter) Notify() {
 	sessVal := s.Session().GetMultiple()
 	userId := common.ObjToString(sessVal["userId"])
 	log.Println("message  userId:", userId)
+	if userId == "" {
+		userId = common.InterfaceToStr(s.Session().Id())
+	}
 	//userId = s.GetString("userId")
-	//log.Println("params  userId:", s.GetString("userId"))
+	log.Println("params  userId:", s.GetString("userId"))
 	if userId != "" {
 		// 创建用户专属的消息通道
 		messageChan := make(chan string)
@@ -49,14 +52,18 @@ func (s *ServerSentRouter) Notify() {
 		}()
 		// 监听消息通道并发送给客户端
 		flusher := s.ResponseWriter.(http.Flusher)
+		ticker := time.NewTicker(15 * time.Second)
+		defer ticker.Stop()
 		for {
 			select {
 			case msg := <-messageChan:
 				fmt.Fprintf(s.ResponseWriter, "data: %s\n\n", msg)
-				flusher.Flush()
+			case <-ticker.C:
+				fmt.Fprintf(s.ResponseWriter, ": heartbeat\n\n")
 			case <-s.Request.Context().Done():
 				return // 客户端断开连接
 			}
+			flusher.Flush()
 		}
 	} else {
 		s.ServeJson("not login")