-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathconn.go
246 lines (211 loc) · 5.31 KB
/
conn.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package gws
import (
"bufio"
"bytes"
"crypto/tls"
"encoding/binary"
"net"
"sync/atomic"
"time"
"unicode/utf8"
"github.com/lxzan/gws/internal"
)
type Conn struct {
// store session information
SessionStorage SessionStorage
// is server
isServer bool
// sub protocol
subprotocol string
// whether to use compression
compressEnabled bool
// tcp connection
conn net.Conn
// configs
config *Config
// read buffer
br *bufio.Reader
// continuation frame
continuationFrame continuationFrame
// frame header for read
fh frameHeader
// WebSocket Event Handler
handler Event
// whether server is closed
closed uint32
// async read task queue
readQueue workerQueue
// async write task queue
writeQueue workerQueue
// flate compressor
compressor *compressor
// flate decompressor
decompressor *decompressor
}
func serveWebSocket(isServer bool, config *Config, session SessionStorage, netConn net.Conn, br *bufio.Reader, handler Event, compressEnabled bool, subprotocol string) *Conn {
c := &Conn{
isServer: isServer,
SessionStorage: session,
config: config,
compressEnabled: compressEnabled,
conn: netConn,
closed: 0,
br: br,
fh: frameHeader{},
handler: handler,
readQueue: workerQueue{maxConcurrency: int32(config.ReadAsyncGoLimit)},
writeQueue: workerQueue{maxConcurrency: 1},
subprotocol: subprotocol,
}
if compressEnabled {
c.compressor = config.compressors.Select()
c.decompressor = config.decompressors.Select()
}
return c
}
// ReadLoop start a read message loop
// 启动一个读消息的死循环
func (c *Conn) ReadLoop() {
defer c.conn.Close()
c.handler.OnOpen(c)
for {
if err := c.readMessage(); err != nil {
c.emitError(err)
return
}
}
}
func (c *Conn) isTextValid(opcode Opcode, payload []byte) bool {
if !c.config.CheckUtf8Enabled {
return true
}
switch opcode {
case OpcodeText, OpcodeCloseConnection:
return utf8.Valid(payload)
default:
return true
}
}
func (c *Conn) isClosed() bool {
return atomic.LoadUint32(&c.closed) == 1
}
func (c *Conn) emitError(err error) {
if err == nil {
return
}
var responseCode = internal.CloseNormalClosure
var responseErr error = internal.CloseNormalClosure
switch v := err.(type) {
case internal.StatusCode:
responseCode = v
case *internal.Error:
responseCode = v.Code
responseErr = v.Err
default:
responseErr = err
}
var content = responseCode.Bytes()
content = append(content, err.Error()...)
if len(content) > internal.ThresholdV1 {
content = content[:internal.ThresholdV1]
}
if atomic.CompareAndSwapUint32(&c.closed, 0, 1) {
_ = c.doWrite(OpcodeCloseConnection, content)
_ = c.conn.SetDeadline(time.Now())
c.handler.OnClose(c, responseErr)
}
}
func (c *Conn) emitClose(buf *bytes.Buffer) error {
var responseCode = internal.CloseNormalClosure
var realCode = internal.CloseNormalClosure.Uint16()
switch buf.Len() {
case 0:
responseCode = 0
realCode = 0
case 1:
responseCode = internal.CloseProtocolError
realCode = uint16(buf.Bytes()[0])
buf.Reset()
default:
var b [2]byte
_, _ = buf.Read(b[0:])
realCode = binary.BigEndian.Uint16(b[0:])
switch realCode {
case 1004, 1005, 1006, 1014, 1015:
responseCode = internal.CloseProtocolError
default:
if realCode < 1000 || realCode >= 5000 || (realCode >= 1016 && realCode < 3000) {
responseCode = internal.CloseProtocolError
} else if realCode < 1016 {
responseCode = internal.CloseNormalClosure
} else {
responseCode = internal.StatusCode(realCode)
}
}
if !c.isTextValid(OpcodeCloseConnection, buf.Bytes()) {
responseCode = internal.CloseUnsupportedData
}
}
if atomic.CompareAndSwapUint32(&c.closed, 0, 1) {
_ = c.doWrite(OpcodeCloseConnection, responseCode.Bytes())
c.handler.OnClose(c, &CloseError{Code: realCode, Reason: buf.Bytes()})
}
return internal.CloseNormalClosure
}
// SetDeadline sets deadline
func (c *Conn) SetDeadline(t time.Time) error {
if c.isClosed() {
return ErrConnClosed
}
err := c.conn.SetDeadline(t)
c.emitError(err)
return err
}
// SetReadDeadline sets read deadline
func (c *Conn) SetReadDeadline(t time.Time) error {
if c.isClosed() {
return ErrConnClosed
}
err := c.conn.SetReadDeadline(t)
c.emitError(err)
return err
}
// SetWriteDeadline sets write deadline
func (c *Conn) SetWriteDeadline(t time.Time) error {
if c.isClosed() {
return ErrConnClosed
}
err := c.conn.SetWriteDeadline(t)
c.emitError(err)
return err
}
func (c *Conn) LocalAddr() net.Addr {
return c.conn.LocalAddr()
}
func (c *Conn) RemoteAddr() net.Addr {
return c.conn.RemoteAddr()
}
// NetConn get tcp/tls/kcp... connection
func (c *Conn) NetConn() net.Conn {
return c.conn
}
// SetNoDelay controls whether the operating system should delay
// packet transmission in hopes of sending fewer packets (Nagle's
// algorithm). The default is true (no delay), meaning that data is
// sent as soon as possible after a Write.
func (c *Conn) SetNoDelay(noDelay bool) error {
switch v := c.conn.(type) {
case *net.TCPConn:
return v.SetNoDelay(noDelay)
case *tls.Conn:
if netConn, ok := v.NetConn().(*net.TCPConn); ok {
return netConn.SetNoDelay(noDelay)
}
}
return nil
}
// SubProtocol 获取协商的子协议
// Get negotiated sub-protocols
func (c *Conn) SubProtocol() string {
return c.subprotocol
}