diff --git a/controllers/event_controller.go b/controllers/event_controller.go index 82989db03..c6a1cfda5 100644 --- a/controllers/event_controller.go +++ b/controllers/event_controller.go @@ -32,7 +32,7 @@ type EventController struct { } //连接的客户端,吧每个客户端都放进来 -var clients = make(map[int][]*websocket.Conn) +var clients = make(map[int]map[string]*websocket.Conn) //广播频道(通道) var broadcast = make(chan map[int]*model.ImMessageRecord) @@ -88,9 +88,9 @@ func (c *EventController) TestWebsocket() { } defer ws.Close() var ( - userID = c.GetString("userID") - msgMap = make(map[int]*model.ImMessageRecord) - groupID int + userID = c.GetString("userID") + msgMap = make(map[int]*model.ImMessageRecord) + clientUser = make(map[string]*websocket.Conn) ) //将当前客户端放入map中 messageGroups, _ := dao.GetUserMessageGroups(dao.GetDB(), userID) @@ -98,7 +98,8 @@ func (c *EventController) TestWebsocket() { return } for _, v := range messageGroups { - clients[v.GroupID] = append(clients[v.GroupID], ws) + clientUser[userID] = ws + clients[v.GroupID] = clientUser } db := dao.GetDB() if globals.IsProductEnv() { @@ -121,18 +122,7 @@ func (c *EventController) TestWebsocket() { err := ws.ReadJSON(&s) if err != nil { globals.SugarLogger.Debugf("页面可能断开啦 ws.ReadJSON error: %v", err.Error()) - index := 0 - for k, v := range clients[groupID] { - if v == ws { - index = k - } - } - wsList := clients[groupID] - if len(wsList) > 0 { - clients[groupID] = clients[groupID][0:0] - clients[groupID] = append(clients[groupID], wsList[0:index]...) - clients[groupID] = append(clients[groupID], wsList[index+1:len(wsList)]...) - } + delete(clients[s.GroupID], s.UserID) // delete(clients, ws) //删除map中的客户端 break //结束循环 } else { @@ -170,18 +160,7 @@ func handleMessages() { if err != nil { globals.SugarLogger.Debugf("client.WriteJSON error: %v", err) client.Close() //关闭 - index := 0 - for k, v := range clients[groupID] { - if v == client { - index = k - } - } - wsList := clients[groupID] - if len(wsList) > 0 { - clients[groupID] = clients[groupID][0:0] - clients[groupID] = append(clients[groupID], wsList[0:index]...) - clients[groupID] = append(clients[groupID], wsList[index+1:len(wsList)]...) - } + delete(clients[mmsg.GroupID], mmsg.UserID) // delete(clients, client) //删除map中的客户端 } }