-
Notifications
You must be signed in to change notification settings - Fork 148
/
keepalive.go
54 lines (46 loc) · 1015 Bytes
/
keepalive.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package proxy
import (
"time"
"github.com/gorilla/websocket"
)
type KeepAlive struct {
conn *websocket.Conn
pongChan chan struct{}
keepAliveInterval time.Duration
}
func NewKeepAlive(conn *websocket.Conn, keepAliveInterval time.Duration) *KeepAlive {
return &KeepAlive{
conn: conn,
pongChan: make(chan struct{}, 1),
keepAliveInterval: keepAliveInterval,
}
}
func (k *KeepAlive) Run() {
k.conn.SetPongHandler(k.pongHandler)
defer k.conn.SetPongHandler(nil)
timeout := time.NewTimer(k.keepAliveInterval)
for {
err := k.conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(5*time.Second))
if err != nil {
return
}
if !timeout.Stop() {
<-timeout.C
}
timeout.Reset(k.keepAliveInterval)
select {
case <-k.pongChan:
time.Sleep(k.keepAliveInterval / 2)
continue
case <-timeout.C:
return
}
}
}
func (k *KeepAlive) pongHandler(string) error {
select {
case k.pongChan <- struct{}{}:
default:
}
return nil
}