add ws
This commit is contained in:
parent
fe9d0650dc
commit
16b26c28ba
|
|
@ -66,6 +66,7 @@ func SetUpIMGroup(router *gin.Engine) {
|
|||
imGroup.POST("/accept_invite", AcceptInvite)
|
||||
imGroup.POST("/create_group", CreateGroup)
|
||||
imGroup.GET("/sse_msg", ServerSendMsg)
|
||||
imGroup.GET("/ws_v2", ServerSsendMsgV2)
|
||||
imGroup.POST("/get_friend_list", GetFriendList) //获取好友列表,包括群聊
|
||||
}
|
||||
func generateRandomHexString(length int) (string, error) {
|
||||
|
|
@ -338,6 +339,63 @@ func SRMessage(c *gin.Context) {
|
|||
}
|
||||
}
|
||||
|
||||
func ServerSsendMsgV2(c *gin.Context) {
|
||||
//wss
|
||||
id, _ := c.Get("id")
|
||||
user_id := int(id.(float64))
|
||||
|
||||
// 升级HTTP连接为WebSocket连接
|
||||
ws, err1 := upgrader.Upgrade(c.Writer, c.Request, nil)
|
||||
clients[ws] = true
|
||||
if err1 != nil {
|
||||
// log.Println(err)
|
||||
fmt.Println(err1)
|
||||
return
|
||||
}
|
||||
defer ws.Close()
|
||||
//设置用户在线状态
|
||||
worker.SetRedisWithExpire("user_"+strconv.Itoa(user_id)+"_status_v2", "1", time.Second*60)
|
||||
//发送消息
|
||||
|
||||
key := "user_" + strconv.Itoa(user_id) + "_msg_ids"
|
||||
|
||||
for {
|
||||
msg_id := worker.PopRedisListLeft(key)
|
||||
if msg_id != "" {
|
||||
msg_id_num, _ := strconv.ParseInt(msg_id, 10, 64)
|
||||
msgs := dao.FindMessageByID(uint(msg_id_num))
|
||||
if len(msgs) > 0 {
|
||||
msg := msgs[0]
|
||||
//发送消息
|
||||
msg_str, _ := json.Marshal(msg)
|
||||
_, err := c.Writer.Write([]byte("data: " + string(msg_str) + "\n\n"))
|
||||
if err != nil {
|
||||
worker.SetRedisWithExpire("user_"+strconv.Itoa(user_id)+"_status_v2", "0", time.Second*3600)
|
||||
clientsMux.Lock()
|
||||
delete(clients, ws)
|
||||
clientsMux.Unlock()
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
var msg proto.Message
|
||||
msg.Type = "check"
|
||||
msg.Msg = "check"
|
||||
msg.From_user_id = -1
|
||||
//发送心跳包
|
||||
res3, _ := json.Marshal(msg)
|
||||
_, err := c.Writer.Write([]byte("data: " + string(res3) + "\n\n"))
|
||||
if err != nil {
|
||||
worker.SetRedisWithExpire("user_"+strconv.Itoa(user_id)+"_status_v2", "0", time.Second*3600)
|
||||
clientsMux.Lock()
|
||||
delete(clients, ws)
|
||||
clientsMux.Unlock()
|
||||
break
|
||||
}
|
||||
}
|
||||
time.Sleep(time.Second * 1)
|
||||
}
|
||||
}
|
||||
func ServerSendMsg(c *gin.Context) {
|
||||
//sse
|
||||
c.Writer.Header().Set("Content-Type", "text/event-stream")
|
||||
|
|
|
|||
Loading…
Reference in New Issue