forked from rancher/remotedialer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wsconn.go
47 lines (39 loc) · 984 Bytes
/
wsconn.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
package remotedialer
import (
"io"
"sync"
"time"
"github.com/gorilla/websocket"
)
type wsConn struct {
sync.Mutex
conn *websocket.Conn
}
func newWSConn(conn *websocket.Conn) *wsConn {
w := &wsConn{
conn: conn,
}
w.setupDeadline()
return w
}
func (w *wsConn) WriteMessage(messageType int, data []byte) error {
w.Lock()
defer w.Unlock()
w.conn.SetWriteDeadline(time.Now().Add(PingWaitDuration))
return w.conn.WriteMessage(messageType, data)
}
func (w *wsConn) NextReader() (int, io.Reader, error) {
return w.conn.NextReader()
}
func (w *wsConn) setupDeadline() {
w.conn.SetReadDeadline(time.Now().Add(PingWaitDuration))
w.conn.SetPingHandler(func(string) error {
w.Lock()
w.conn.WriteControl(websocket.PongMessage, []byte(""), time.Now().Add(time.Second))
w.Unlock()
return w.conn.SetReadDeadline(time.Now().Add(PingWaitDuration))
})
w.conn.SetPongHandler(func(string) error {
return w.conn.SetReadDeadline(time.Now().Add(PingWaitDuration))
})
}