Skip to content

Commit

Permalink
Provide a simple callback function for when you need to know a ping c…
Browse files Browse the repository at this point in the history
…ame in. This should address #246.
  • Loading branch information
schmidtw committed Dec 19, 2023
1 parent e3a2d32 commit da4bc3c
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
9 changes: 9 additions & 0 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ type Conn struct {
pingCounter int32
activePingsMu sync.Mutex
activePings map[string]chan<- struct{}

pingCallback func()
}

type connConfig struct {
Expand Down Expand Up @@ -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{}
Expand Down
3 changes: 3 additions & 0 deletions read.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit da4bc3c

Please sign in to comment.