/
wsclient.go
202 lines (168 loc) · 3.96 KB
/
wsclient.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
package y
import (
"context"
"github.com/gorilla/websocket"
"net"
"time"
)
const (
writeChanSize = 256
readTimeout = 10 * time.Second
writeTimeout = 10 * time.Second
tagClient = "C"
tagServer = "S"
)
type WSClient struct {
conn *websocket.Conn
id uint64
closed bool
writeChan chan []byte
hbChan chan struct{}
cancel context.CancelFunc
userID interface{}
lastTime time.Time
Parser IParser
State IState
}
func (c *WSClient) read(tag string) {
defer RecoverError()
defer c.Close()
if tag == tagServer {
c.conn.SetPingHandler(func(message string) error {
Debugf("%s IClient.read got ping id = %d", tag, c.id)
c.lastTime = time.Now()
err := c.conn.WriteControl(websocket.PongMessage, []byte(message), time.Now().Add(writeTimeout))
if err == websocket.ErrCloseSent {
return nil
} else if e, ok := err.(net.Error); ok && e.Temporary() {
return nil
}
//Debug("PONG")
return err
})
} else if tag == tagClient {
c.conn.SetPongHandler(func(message string) error {
Debugf("%s IClient.read got pong id = %d", tag, c.id)
return nil
})
}
for {
_, buf, err := c.conn.ReadMessage()
if err != nil {
if !c.closed {
Errorf("%s IClient.read error id = %d, %+v", tag, c.id, err)
}
return
}
err = c.Parser.OnNewData(c, buf)
if err != nil {
Errorf("%s IClient.read %+v", tag, err)
break
}
c.lastTime = time.Now()
}
}
func (c *WSClient) write(ctx context.Context, tag string) {
defer RecoverError()
for {
select {
case buf := <-c.writeChan:
c.conn.SetWriteDeadline(time.Now().Add(time.Duration(writeTimeout)))
err := c.conn.WriteMessage(websocket.BinaryMessage, buf)
if err != nil {
Errorf("%s IClient.write error id = %d, %+v, %+v", tag, c.id, err, buf)
}
case <-c.hbChan:
err := c.conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(time.Duration(writeTimeout)))
if err != nil {
Errorf("%s IClient.write ping error id = %d, %+v, %+v", tag, c.id, err)
}
case <-ctx.Done():
Debugf("%s IClient.write done id = %d", tag, c.id)
return
}
}
}
func (c *WSClient) startHeartbeat(ctx context.Context, dur time.Duration) {
defer RecoverError()
ticker := time.NewTicker(dur)
defer ticker.Stop()
for {
select {
case <-ticker.C:
c.hbChan <- struct{}{}
case <-ctx.Done():
Debugf("IClient.StartHeartbeat done id = %d", c.id)
return
}
}
}
func (c *WSClient) Close() {
defer RecoverError()
if !c.closed {
c.closed = true
c.cancel()
c.conn.Close()
if c.State != nil {
c.State.OnClose(c)
}
}
}
func (c *WSClient) Send(data []byte) {
if len(data) == 0 {
return
}
c.writeChan <- data
}
func (c *WSClient) ConnId() uint64 {
return c.id
}
func (c *WSClient) UserId() interface{} {
return c.userID
}
func (c *WSClient) LastTime() time.Time {
return c.lastTime
}
func newWSClientServerSide(ctx context.Context, id uint64, conn *websocket.Conn, userId interface{}, parser IParser, state IState) (client *WSClient, err error) {
ctx, cancel := context.WithCancel(ctx)
client = &WSClient{
conn: conn,
id: id,
closed: false,
writeChan: make(chan []byte, writeChanSize),
userID: userId,
lastTime: time.Now(),
cancel: cancel,
Parser: parser,
State: state,
}
go client.read(tagServer)
go client.write(ctx, tagServer)
return
}
type WSClientDialer struct {
*websocket.Dialer
Heartbeat time.Duration
}
func (d *WSClientDialer) Dial(ctx context.Context, connection string, id uint64) (client *WSClient, err error) {
ctx, cancel := context.WithCancel(ctx)
conn, _, err := d.DialContext(ctx, connection, nil)
if err != nil {
return
}
client = &WSClient{
conn: conn,
id: id,
closed: false,
writeChan: make(chan []byte, writeChanSize),
hbChan: make(chan struct{}, 1),
lastTime: time.Now(),
cancel: cancel,
}
go client.read(tagClient)
go client.write(ctx, tagClient)
if d.Heartbeat > 0 {
go client.startHeartbeat(ctx, d.Heartbeat)
}
return
}