From ef1c967044c84f414eb0a4fa89d71c2c6eed90a7 Mon Sep 17 00:00:00 2001 From: Sigmar Stefansson Date: Tue, 2 Apr 2024 13:26:59 +0000 Subject: [PATCH] add ticker for periodic websocket ping --- internal/cmd/ocean/spark_connect.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/internal/cmd/ocean/spark_connect.go b/internal/cmd/ocean/spark_connect.go index f8fc1657..16aba6f2 100644 --- a/internal/cmd/ocean/spark_connect.go +++ b/internal/cmd/ocean/spark_connect.go @@ -274,6 +274,9 @@ func handleSocketConnection(ctx context.Context, conn net.Conn, wsConn *websocke return fromUpstream(conn, wsConn) }) + // Send websocket ping periodically to keep connection alive + g.Go(func() error { return sendPing(ctx, wsConn) }) + return g.Wait() } @@ -315,3 +318,19 @@ func toUpstream(downstream io.Writer, upstream *websocket.Conn) error { return nil } + +func sendPing(ctx context.Context, wsConn *websocket.Conn) error { + ticker := time.NewTicker(5 * time.Second) + defer ticker.Stop() + + for { + select { + case <-ctx.Done(): + return nil + case <-ticker.C: + if err := wsConn.WriteMessage(websocket.PingMessage, nil); err != nil { + return err + } + } + } +}