Skip to content
Permalink
Browse files

Set up pings on client side of websocket to detect stale sockets

  • Loading branch information...
justone committed Aug 25, 2019
1 parent dda1b01 commit 07760d0c861fbfc8906153177d0086bd2b13a75c
Showing with 27 additions and 0 deletions.
  1. +27 −0 api/ws.go
@@ -7,6 +7,13 @@ import (
"github.com/gorilla/websocket"
)

const (
writeWait = 10 * time.Second
pongWait = 60 * time.Second
pingPeriod = (pongWait * 9) / 10
maxMessageSize = 256 * 1024
)

func connectWS(URI string, id string, sub string) (*Connection, error) {

in := make(chan Message, 10)
@@ -78,6 +85,14 @@ func connectSocket(uri string) (*websocket.Conn, error) {
return nil, err
}

c.SetReadLimit(maxMessageSize)
c.SetReadDeadline(time.Now().Add(pongWait))
c.SetPongHandler(func(string) error {
logrus.Debugf("received pong")
c.SetReadDeadline(time.Now().Add(pongWait))
return nil
})

return c, err
}

@@ -106,6 +121,11 @@ func processSocket(pmbConn *Connection, conn *websocket.Conn, id string) {

// Set up writer side of socket
go func() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
conn.Close()
}()
for {
select {
case <-done:
@@ -119,6 +139,7 @@ func processSocket(pmbConn *Connection, conn *websocket.Conn, id string) {
}

for _, body := range bodies {
conn.SetWriteDeadline(time.Now().Add(writeWait))
err = conn.WriteMessage(websocket.TextMessage, body)
if err != nil {
logrus.Errorf("error writing:", err)
@@ -130,6 +151,12 @@ func processSocket(pmbConn *Connection, conn *websocket.Conn, id string) {
logrus.Debugf("Done channel present, sending message")
message.Done <- nil
}
case <-ticker.C:
conn.SetWriteDeadline(time.Now().Add(writeWait))
logrus.Debugf("sending ping")
if err := conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}()

0 comments on commit 07760d0

Please sign in to comment.
You can’t perform that action at this time.