Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
support set pinghandler and ponghandler
  • Loading branch information
qcha0 committed Jun 11, 2021
commit 259dca8e9be3594aaead6aadc0992f6a32693f71
5 changes: 5 additions & 0 deletions conn_notjs.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ type Conn struct {
pingCounter int32
activePingsMu sync.Mutex
activePings map[string]chan<- struct{}
pingHandler func(ctx context.Context, p []byte) error
pongHandler func(ctx context.Context, p []byte) error
}

type connConfig struct {
Expand Down Expand Up @@ -89,6 +91,9 @@ func newConn(cfg connConfig) *Conn {
closed: make(chan struct{}),
activePings: make(map[string]chan<- struct{}),
}
// set default ping, pong handler
c.SetPingHandler(nil)
c.SetPongHandler(nil)

c.readMu = newMu(c)
c.writeFrameMu = newMu(c)
Expand Down
28 changes: 26 additions & 2 deletions read.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,30 @@ func (c *Conn) SetReadLimit(n int64) {
c.msgReader.limitReader.limit.Store(n + 1)
}

// SetPingHandler set the handler for pong handler
// From 5.5.2 of RFC 6455
// "Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in response"
func (c *Conn) SetPingHandler(f func(ctx context.Context, p []byte) error) {
c.pingHandler = func(ctx context.Context, p []byte) error {
if err := c.writeControl(ctx, opPong, p); err != nil {
return err
}
if f != nil {
return f(ctx, p)
}
return nil
}
}

// SetPongHandler set the handler for ping message
// By default, do nothing
func (c *Conn) SetPongHandler(f func(ctx context.Context, p []byte) error) {
if f == nil {
f = func(context.Context, []byte) error { return nil }
}
c.pongHandler = f
}

const defaultReadLimit = 32768

func newMsgReader(c *Conn) *msgReader {
Expand Down Expand Up @@ -265,7 +289,7 @@ func (c *Conn) handleControl(ctx context.Context, h header) (err error) {

switch h.opcode {
case opPing:
return c.writeControl(ctx, opPong, b)
return c.pingHandler(ctx, b)
case opPong:
c.activePingsMu.Lock()
pong, ok := c.activePings[string(b)]
Expand All @@ -276,7 +300,7 @@ func (c *Conn) handleControl(ctx context.Context, h header) (err error) {
default:
}
}
return nil
return c.pongHandler(ctx, b)
}

defer func() {
Expand Down