summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorShulhan <m.shulhan@gmail.com>2020-04-29 14:55:24 +0700
committerShulhan <m.shulhan@gmail.com>2020-04-29 14:57:33 +0700
commit35acee7bf8a86d319cebbcc2f001521f8e2fc6f0 (patch)
treeee40c1977c3f06ba0b9e0370da99179468cc6493
parent4604e292c97fc2d5c06d2d56e581599aa0a6e7c7 (diff)
downloadpakakeh.go-35acee7bf8a86d319cebbcc2f001521f8e2fc6f0.tar.xz
websocket: add routine that send PING control frame on Connect
The send interval can be set in Client.PingInterval. The minimum and default value is 10 seconds.
-rw-r--r--lib/websocket/client.go28
-rw-r--r--lib/websocket/websocket.go3
2 files changed, 30 insertions, 1 deletions
diff --git a/lib/websocket/client.go b/lib/websocket/client.go
index abf38ab6..5976781a 100644
--- a/lib/websocket/client.go
+++ b/lib/websocket/client.go
@@ -7,6 +7,7 @@ package websocket
import (
"bytes"
"crypto/tls"
+ "errors"
"fmt"
"log"
"net"
@@ -145,6 +146,10 @@ type Client struct {
// "sec-websocket-version") will be deleted before handshake.
Headers http.Header
+ // The interval where PING control frame will be send to server.
+ // The minimum and default value is 10 seconds.
+ PingInterval time.Duration
+
remoteURL *url.URL
remoteAddr string
@@ -233,6 +238,11 @@ func (cl *Client) Connect() (err error) {
}
}
+ if cl.PingInterval < defaultPingInterval {
+ cl.PingInterval = defaultPingInterval
+ }
+
+ go cl.pinger()
go cl.serve()
return nil
@@ -851,3 +861,21 @@ func (cl *Client) send(packet []byte) (err error) {
return nil
}
+
+//
+// pinger send the PING control frame every 10 seconds.
+//
+func (cl *Client) pinger() {
+ var err error
+
+ t := time.NewTicker(cl.PingInterval)
+ for range t.C {
+ err = cl.SendPing(nil)
+ if err != nil {
+ if errors.Is(err, ErrConnClosed) {
+ return
+ }
+ log.Println("websocket: pinger: " + err.Error())
+ }
+ }
+}
diff --git a/lib/websocket/websocket.go b/lib/websocket/websocket.go
index a66cf439..69833fbd 100644
--- a/lib/websocket/websocket.go
+++ b/lib/websocket/websocket.go
@@ -26,7 +26,8 @@ const (
//nolint:gochecknoglobals
var (
- defaultTimeout = 10 * time.Second
+ defaultTimeout = 10 * time.Second
+ defaultPingInterval = 10 * time.Second
_bbPool = sync.Pool{
New: func() interface{} {