forked from okb48/pusher-websocket-go
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
connection.go
194 lines (157 loc) · 3.97 KB
/
connection.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package pusher
import (
// "fmt"
"github.com/gorilla/websocket"
"log"
"net/url"
"time"
)
var Debug = false
const (
pusherProtocol = "7"
clientName = "pusher-websocket-go"
clientVersion = "0.0.1"
// Same as defined in websocket
writeWait = time.Second
// Send pongs after this time. The server inactivity timeout is 120s.
defaultInactivityTimeout = 100 * time.Second
// Wait this long for pong replies before closing the connection
pongTimeout = 5000 * time.Millisecond
)
type connCallbacks struct {
onMessage chan<- string
onClose chan<- bool
onDisconnect chan bool
}
// Connection responsibilities:
//
// * Providing a channel based interface on top of the WebSocket library
// * Connecting to the Pusher WebSocket interface
// * Triggering pings on periods of inactivity, and disconnecting if server does not reply
// * Exposing disconnect reason
//
type connection struct {
config *connCallbacks
inactivityTimeout time.Duration
_sendMessage chan []byte
_onMessage chan string
_onPingPong chan bool
_onClose chan error
ws *websocket.Conn
socketID string
connected bool
}
func dial(c ClientConfig, conf *connCallbacks) (conn *connection, err error) {
baseURL := c.Scheme + "://" + c.Host + ":" + c.Port + "/app/" + c.Key
params := url.Values{}
params.Set("protocol", pusherProtocol)
params.Set("client", clientName)
params.Set("version", clientVersion)
url := baseURL + "?" + params.Encode()
ws, _, err := websocket.DefaultDialer.Dial(url, nil)
conn = &connection{
inactivityTimeout: defaultInactivityTimeout,
config: conf,
_sendMessage: make(chan []byte, 10),
_onMessage: make(chan string),
_onPingPong: make(chan bool),
_onClose: make(chan error),
ws: ws,
}
// TODO: Is this blocking as it connects?
if err == nil {
ws.SetPingHandler(func(msg string) error {
// TODO: Check that this is safe
ws.WriteControl(websocket.PongMessage, []byte(msg), time.Now().Add(writeWait))
conn._onPingPong <- true
return nil
})
ws.SetPongHandler(func(msg string) error {
conn._onPingPong <- true
return nil
})
go conn.readLoop()
go conn.runLoop()
}
return
}
func (self *connection) send(message []byte) {
self._sendMessage <- message
}
func (self *connection) readLoop() {
ws := self.ws
for {
if _, msg, err := ws.ReadMessage(); err == nil {
self._onMessage <- string(msg)
} else {
// TODO: Read the close code
if err.Error() == "EOF" {
if Debug {
log.Print("Disconnected")
}
} else {
if Debug {
log.Print("Closed: ", err)
}
self._onClose <- err
}
return
}
}
}
func (self *connection) runLoop() {
pingTimer := time.NewTimer(self.inactivityTimeout)
awaitingPong := false
afterActivity := func() {
pingTimer.Reset(self.inactivityTimeout)
awaitingPong = false
}
ws := self.ws
for {
select {
case <-pingTimer.C:
if awaitingPong == false {
if Debug {
log.Printf("No activity in %v, sending ping", self.inactivityTimeout)
}
ws.WriteControl(websocket.PingMessage, nil, time.Now().Add(writeWait))
// Wait a further pong timeout
pingTimer.Reset(pongTimeout)
awaitingPong = true
} else {
if Debug {
log.Print("Closing after non-receipt of pong")
}
ws.Close()
}
case <-self._onClose:
if self.config.onClose != nil {
self.config.onClose <- true
}
return
case <-self.config.onDisconnect:
ws.WriteControl(websocket.CloseMessage, nil, time.Now().Add(writeWait))
if Debug {
log.Print("Disconnecting...")
}
return
case msg := <-self._onMessage:
afterActivity()
if self.config.onMessage != nil {
self.config.onMessage <- msg
}
case <-self._onPingPong:
afterActivity()
case msg := <-self._sendMessage:
if Debug {
log.Print("Sending: ", string(msg))
}
err := ws.WriteMessage(websocket.TextMessage, msg)
if err != nil {
if Debug {
log.Print("Error sending: ", err)
}
}
}
}
}