mirror of
https://gitee.com/dromara/mayfly-go
synced 2025-12-26 01:16:36 +08:00
refactor: 系统websocket消息重构
This commit is contained in:
@@ -1,10 +1,7 @@
|
||||
package ws
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"mayfly-go/pkg/logx"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
@@ -17,58 +14,24 @@ var Upgrader = websocket.Upgrader{
|
||||
},
|
||||
}
|
||||
|
||||
var conns = make(map[uint64]*websocket.Conn, 100)
|
||||
var Manager = NewClientManager() // 管理者
|
||||
|
||||
func init() {
|
||||
checkConn()
|
||||
go Manager.Start()
|
||||
}
|
||||
|
||||
// 放置ws连接
|
||||
func Put(userId uint64, conn *websocket.Conn) {
|
||||
existConn := conns[userId]
|
||||
if existConn != nil {
|
||||
Delete(userId)
|
||||
}
|
||||
|
||||
conn.SetCloseHandler(func(code int, text string) error {
|
||||
Delete(userId)
|
||||
return nil
|
||||
})
|
||||
conns[userId] = conn
|
||||
// 添加ws客户端
|
||||
func AddClient(userId uint64, conn *websocket.Conn) *Client {
|
||||
cli := NewClient(UserId(userId), conn)
|
||||
Manager.AddClient(cli)
|
||||
return cli
|
||||
}
|
||||
|
||||
func checkConn() {
|
||||
heartbeat := time.Duration(60) * time.Second
|
||||
tick := time.NewTicker(heartbeat)
|
||||
go func() {
|
||||
for range tick.C {
|
||||
// 遍历所有连接,ping失败的则删除掉
|
||||
for uid, conn := range conns {
|
||||
err := conn.WriteControl(websocket.PingMessage, []byte("ping"), time.Now().Add(heartbeat/2))
|
||||
if err != nil {
|
||||
Delete(uid)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// 删除ws连接
|
||||
func Delete(userid uint64) {
|
||||
logx.Debugf("移除websocket连接: uid = %d", userid)
|
||||
conn := conns[userid]
|
||||
if conn != nil {
|
||||
conn.Close()
|
||||
delete(conns, userid)
|
||||
}
|
||||
func CloseClient(userid uint64) {
|
||||
Manager.CloseByUid(UserId(userid))
|
||||
}
|
||||
|
||||
// 对指定用户发送消息
|
||||
func SendMsg(userId uint64, msg *Msg) {
|
||||
conn := conns[userId]
|
||||
if conn != nil {
|
||||
bytes, _ := json.Marshal(msg)
|
||||
conn.WriteMessage(websocket.TextMessage, bytes)
|
||||
}
|
||||
func SendMsg(userId uint64, msg *SysMsg) {
|
||||
Manager.SendJsonMsg(UserId(userId), msg)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user