fix: agent ws connect panic

This commit is contained in:
engigu
2026-01-01 13:58:27 +08:00
parent c29fb178a2
commit ac44bc450b
3 changed files with 6 additions and 23 deletions
+1 -19
View File
@@ -189,22 +189,6 @@ func (a *Agent) connectWS() error {
return err return err
} }
// 设置读取超时(比服务端 ping 间隔长一些)
conn.SetReadDeadline(time.Now().Add(60 * time.Second))
// 设置 Ping 处理器,收到 Ping 时重置读取超时
conn.SetPingHandler(func(appData string) error {
conn.SetReadDeadline(time.Now().Add(60 * time.Second))
// 回复 Pong
return conn.WriteControl(websocket.PongMessage, []byte(appData), time.Now().Add(5*time.Second))
})
// 设置 Pong 处理器,收到 Pong 时重置读取超时
conn.SetPongHandler(func(appData string) error {
conn.SetReadDeadline(time.Now().Add(60 * time.Second))
return nil
})
a.wsMu.Lock() a.wsMu.Lock()
a.wsConn = conn a.wsConn = conn
a.wsStopCh = make(chan struct{}) a.wsStopCh = make(chan struct{})
@@ -244,12 +228,10 @@ func (a *Agent) readWS() {
_, message, err := conn.ReadMessage() _, message, err := conn.ReadMessage()
if err != nil { if err != nil {
log.Warnf("WebSocket 读取错误: %v", err)
return return
} }
// 收到消息,重置读取超时
conn.SetReadDeadline(time.Now().Add(60 * time.Second))
var msg WSMessage var msg WSMessage
if err := json.Unmarshal(message, &msg); err != nil { if err := json.Unmarshal(message, &msg); err != nil {
continue continue
+1 -1
View File
@@ -410,7 +410,7 @@ func (c *AgentController) wsReadPump(ac *services.AgentConnection, agent *models
if r := recover(); r != nil { if r := recover(); r != nil {
logger.Errorf("[AgentWS] Agent #%d wsReadPump panic: %v", agent.ID, r) logger.Errorf("[AgentWS] Agent #%d wsReadPump panic: %v", agent.ID, r)
} }
c.wsManager.Unregister(agent.ID) c.wsManager.Unregister(agent.ID, ac)
}() }()
// 检查连接是否有效(可能是旧连接被新连接替换) // 检查连接是否有效(可能是旧连接被新连接替换)
+4 -3
View File
@@ -161,12 +161,13 @@ func (m *AgentWSManager) Register(agentID uint, conn *websocket.Conn, ip string)
return ac return ac
} }
// Unregister 注销连接 // Unregister 注销连接(只注销指定的连接实例)
func (m *AgentWSManager) Unregister(agentID uint) { func (m *AgentWSManager) Unregister(agentID uint, ac *AgentConnection) {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if conn, exists := m.connections[agentID]; exists { // 只有当前连接和 map 中的连接是同一个实例时才删除
if conn, exists := m.connections[agentID]; exists && conn == ac {
// 减少 IP 连接计数 // 减少 IP 连接计数
if conn.IP != "" { if conn.IP != "" {
if count, ok := m.ipConnections[conn.IP]; ok && count > 0 { if count, ok := m.ipConnections[conn.IP]; ok && count > 0 {