@@ -344,6 +344,7 @@ func NewConnection(
344344 initUnderlyingWsConnFn : initUnderlyingWsConnFn ,
345345 keepaliveTimeout : keepaliveTimeout ,
346346 isKeepAliveNeeded : isKeepAliveNeeded ,
347+ done : make (chan struct {}),
347348 }
348349
349350 if isKeepAliveNeeded {
@@ -362,6 +363,7 @@ type connection struct {
362363 initUnderlyingWsConnFn func () (* websocket.Conn , error )
363364 keepaliveTimeout time.Duration
364365 isKeepAliveNeeded bool
366+ done chan struct {}
365367}
366368
367369type Connection interface {
@@ -379,7 +381,11 @@ func (c *connection) WriteMessage(messageType int, data []byte) error {
379381
380382// ReadMessage wrapper for conn.ReadMessage
381383func (c * connection ) ReadMessage () (int , []byte , error ) {
382- return c .conn .ReadMessage ()
384+ msgType , msg , err := c .conn .ReadMessage ()
385+ if err != nil {
386+ close (c .done )
387+ }
388+ return msgType , msg , err
383389}
384390
385391// RestoreConnection recreates ws connection with the same underlying connection callback and keepalive timeout
@@ -401,15 +407,19 @@ func (c *connection) keepAlive(timeout time.Duration) {
401407 defer ticker .Stop ()
402408
403409 for {
404- err := c .ping ()
405- if err != nil {
406- return
407- }
408-
409- <- ticker .C
410- if c .isLastResponseOutdated (timeout ) {
411- c .close ()
410+ select {
411+ case <- c .done :
412412 return
413+ case <- ticker .C :
414+ err := c .ping ()
415+ if err != nil {
416+ return
417+ }
418+
419+ if c .isLastResponseOutdated (timeout ) {
420+ c .close ()
421+ return
422+ }
413423 }
414424 }
415425 }()
@@ -442,10 +452,5 @@ func (c *connection) ping() error {
442452 defer c .connectionMu .Unlock ()
443453
444454 deadline := time .Now ().Add (KeepAlivePingDeadline )
445- err := c .conn .WriteControl (websocket .PingMessage , []byte {}, deadline )
446- if err != nil {
447- return err
448- }
449-
450- return nil
455+ return c .conn .WriteControl (websocket .PingMessage , []byte {}, deadline )
451456}
0 commit comments