From da4bc3cb057f5a382571cbc0b554107b8f644d53 Mon Sep 17 00:00:00 2001 From: schmidtw Date: Mon, 18 Dec 2023 23:27:56 -0800 Subject: [PATCH] Provide a simple callback function for when you need to know a ping came in. This should address #246. --- conn.go | 9 +++++++++ read.go | 3 +++ 2 files changed, 12 insertions(+) diff --git a/conn.go b/conn.go index ef4d62ad..f57cec27 100644 --- a/conn.go +++ b/conn.go @@ -79,6 +79,8 @@ type Conn struct { pingCounter int32 activePingsMu sync.Mutex activePings map[string]chan<- struct{} + + pingCallback func() } type connConfig struct { @@ -251,6 +253,13 @@ func (c *Conn) ping(ctx context.Context, p string) error { } } +// SetPingCallback sets a callback that is called when a ping is received. +// The callback is called synchronously from the Reader goroutine and must +// not block. +func (c *Conn) SetPingCallback(cb func()) { + c.pingCallback = cb +} + type mu struct { c *Conn ch chan struct{} diff --git a/read.go b/read.go index 8742842e..8f25b338 100644 --- a/read.go +++ b/read.go @@ -294,6 +294,9 @@ func (c *Conn) handleControl(ctx context.Context, h header) (err error) { switch h.opcode { case opPing: + if c.pingCallback != nil { + c.pingCallback() + } return c.writeControl(ctx, opPong, b) case opPong: c.activePingsMu.Lock()