Skip to content

Commit ece7d7d

Browse files
committed
fix(client): 增强WebSocket消息处理与心跳机制
- 为WebSocket消息读取设置超时,确保有足够时间接收消息 - 在心跳发送失败时主动关闭连接以触发重连机制,并记录警告日志
1 parent fb68c5f commit ece7d7d

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

internal/client/ws_message_handler.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,11 @@ func (c *WSClient) handleWSMessages() error {
4949
return errors.New("连接已关闭")
5050
}
5151

52-
_, data, err := conn.Read(c.ctx)
52+
// 设置读取超时(心跳间隔的 3 倍,确保有足够时间接收消息)
53+
readCtx, readCancel := context.WithTimeout(c.ctx, heartbeatInterval*3)
54+
_, data, err := conn.Read(readCtx)
55+
readCancel()
56+
5357
if err != nil {
5458
if errors.Is(err, context.Canceled) {
5559
return nil

internal/client/ws_sender.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,13 @@ func (c *WSClient) sendHeartbeat(ctx context.Context) {
107107
}
108108

109109
if err := c.sendNotifyRequest(req); err != nil {
110+
logger.Warn("发送心跳失败,主动关闭连接以触发重连", "error", err)
111+
// 主动关闭连接,触发重连机制
112+
c.connMu.Lock()
113+
if c.conn != nil {
114+
c.conn.Close(websocket.StatusAbnormalClosure, "heartbeat failed")
115+
}
116+
c.connMu.Unlock()
110117
return
111118
}
112119
}

0 commit comments

Comments
 (0)