From 655a19ea742f68cd5d45a1ae75f6ba7663f85fb5 Mon Sep 17 00:00:00 2001 From: Kirguir Date: Mon, 30 Apr 2018 14:27:28 +0300 Subject: [PATCH] Websocket: added OnPong to Connection #986 see issue #986 Former-commit-id: 964d393d40fc7e64a8bf02eae08d97fd5f847483 --- websocket/connection.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/websocket/connection.go b/websocket/connection.go index 3c964879..027ebc75 100644 --- a/websocket/connection.go +++ b/websocket/connection.go @@ -133,6 +133,8 @@ type ( MessageFunc interface{} // PingFunc is the callback which fires each ping PingFunc func() + // PongFunc is the callback which fires on pong message received + PongFunc func() // Connection is the front-end API that you will use to communicate with the client side Connection interface { // Emitter implements EmitMessage & Emit @@ -165,6 +167,8 @@ type ( OnError(ErrorFunc) // OnPing registers a callback which fires on each ping OnPing(PingFunc) + // OnPong registers a callback which fires on pong message received + OnPong(PongFunc) // FireOnError can be used to send a custom error message to the connection // // It does nothing more than firing the OnError listeners. It doesn't send anything to the client. @@ -221,6 +225,7 @@ type ( onRoomLeaveListeners []LeaveRoomFunc onErrorListeners []ErrorFunc onPingListeners []PingFunc + onPongListeners []PongFunc onNativeMessageListeners []NativeMessageFunc onEventListeners map[string][]MessageFunc started bool @@ -256,6 +261,7 @@ func newConnection(ctx context.Context, s *Server, underlineConn UnderlineConnec onErrorListeners: make([]ErrorFunc, 0), onNativeMessageListeners: make([]NativeMessageFunc, 0), onEventListeners: make(map[string][]MessageFunc, 0), + onPongListeners: make([]PongFunc, 0), started: false, ctx: ctx, server: s, @@ -354,6 +360,13 @@ func (c *connection) fireOnPing() { } } +func (c *connection) fireOnPong() { + // fire the onPongListeners + for i := range c.onPongListeners { + c.onPongListeners[i]() + } +} + func (c *connection) startReader() { conn := c.underline hasReadTimeout := c.server.config.ReadTimeout > 0 @@ -363,6 +376,8 @@ func (c *connection) startReader() { if hasReadTimeout { conn.SetReadDeadline(time.Now().Add(c.server.config.ReadTimeout)) } + //fire all OnPong methods + go c.fireOnPong() return nil }) @@ -473,6 +488,10 @@ func (c *connection) OnPing(cb PingFunc) { c.onPingListeners = append(c.onPingListeners, cb) } +func (c *connection) OnPong(cb PongFunc) { + c.onPongListeners = append(c.onPongListeners, cb) +} + func (c *connection) FireOnError(errorMessage string) { for _, cb := range c.onErrorListeners { cb(errorMessage)