-
Notifications
You must be signed in to change notification settings - Fork 22
/
connection.go
218 lines (193 loc) · 5.41 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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
/*
Copyright 2013 Niklas Voss
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package golem
import (
"github.com/gorilla/websocket"
"reflect"
"time"
)
const (
// Time allowed to write a message to the client.
writeWait = 10 * time.Second
// Time allowed to read the next message from the client.
readWait = 60 * time.Second
// Send pings to client with this period. Must be less than readWait.
pingPeriod = (readWait * 9) / 10
// Maximum message size allowed from client.
maxMessageSize = 512
// Outgoing default channel size.
sendChannelSize = 512
)
var (
defaultConnectionExtension = reflect.ValueOf(nil)
)
// SetDefaultConnectionExtension sets the initial extension used by all freshly instanced routers.
// For more information see the Router SetConnectionExtension() - method.
func SetDefaultConnectionExtension(constructor interface{}) {
defaultConnectionExtension = reflect.ValueOf(constructor)
}
// Connection holds information about the underlying WebSocket-Connection,
// the associated router and the outgoing data channel.
type Connection struct {
// The websocket connection.
socket *websocket.Conn
// Associated router.
router *Router
// Buffered channel of outbound messages.
send chan *message
//
extension interface{}
}
// Create a new connection using the specified socket and router.
func newConnection(s *websocket.Conn, r *Router) *Connection {
return &Connection{
socket: s,
router: r,
send: make(chan *message, sendChannelSize),
extension: nil,
}
}
// Register connection and start writing and reading loops.
func (conn *Connection) run() {
hub.register <- conn
readMode := websocket.TextMessage
writeMode := websocket.TextMessage
if conn.router.protocol.GetReadMode() != TextMode {
readMode = websocket.BinaryMessage
}
if conn.router.protocol.GetWriteMode() != TextMode {
writeMode = websocket.BinaryMessage
}
if conn.router.useHeartbeats {
go conn.writePumpHeartbeat(writeMode)
conn.readPumpHeartbeat(readMode)
} else {
go conn.writePump(writeMode)
conn.readPump(readMode)
}
}
func (conn *Connection) extend(e interface{}) {
conn.extension = e
}
// Emit event with provided data. The data will be automatically marshalled and packed according
// to the active protocol of the router the connection belongs to.
func (conn *Connection) Emit(event string, data interface{}) {
conn.send <- &message{
event: event,
data: data,
}
}
// Close closes and cleans up the connection.
func (conn *Connection) Close() {
hub.unregister <- conn
}
// Helper for writing to socket with deadline.
func (conn *Connection) write(mode int, payload []byte) error {
conn.socket.SetWriteDeadline(time.Now().Add(writeWait))
return conn.socket.WriteMessage(mode, payload)
}
/*
* Pumps with Heartbeat.
*/
func (conn *Connection) readPumpHeartbeat(mode int) {
defer func() {
hub.unregister <- conn
conn.socket.Close()
conn.router.closeFunc(conn)
}()
conn.socket.SetReadLimit(maxMessageSize)
conn.socket.SetReadDeadline(time.Now().Add(readWait))
conn.socket.SetPongHandler(func(string) error {
conn.socket.SetReadDeadline(time.Now().Add(readWait))
return nil
})
for {
mm, message, err := conn.socket.ReadMessage()
if err != nil {
break
}
if mm == mode {
conn.router.processMessage(conn, message)
}
}
}
func (conn *Connection) writePumpHeartbeat(mode int) {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
conn.socket.Close() // Necessary to force reading to stop
}()
for {
select {
case message, ok := <-conn.send:
if ok {
if data, err := conn.router.protocol.MarshalAndPack(message.event, message.data); err == nil {
if err := conn.write(mode, data); err != nil {
return
}
} else {
// TODO: logging
}
} else {
conn.write(websocket.CloseMessage, []byte{})
return
}
case <-ticker.C:
if err := conn.write(websocket.PingMessage, []byte{}); err != nil {
return
}
}
}
}
/*
* Pumps without Heartbeat
*/
func (conn *Connection) readPump(mode int) {
defer func() {
hub.unregister <- conn
conn.socket.Close()
conn.router.closeFunc(conn)
}()
conn.socket.SetReadLimit(maxMessageSize)
for {
mm, message, err := conn.socket.ReadMessage()
if err != nil {
break
}
if mm == mode {
conn.router.processMessage(conn, message)
}
}
}
func (conn *Connection) writePump(mode int) {
defer func() {
conn.socket.Close() // Necessary to force reading to stop
}()
for {
select {
case message, ok := <-conn.send:
if ok {
if data, err := conn.router.protocol.MarshalAndPack(message.event, message.data); err == nil {
if err := conn.write(mode, data); err != nil {
return
}
} else {
// TODO: logging
}
} else {
conn.write(websocket.CloseMessage, []byte{})
return
}
}
}
}