-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcometclient.go
More file actions
199 lines (169 loc) · 4.86 KB
/
cometclient.go
File metadata and controls
199 lines (169 loc) · 4.86 KB
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
package main
import (
"bytes"
"fmt"
"net/http"
"time"
"github.com/gorilla/websocket"
)
const (
writeWait = 10 * time.Second
pongWait = 60 * time.Second
maxMessageSize = 4096
//pingPeriod = (pongWait * 9) / 10
pingPeriod = 300 * time.Second
readTimeout = 1200 * time.Second
)
var wsupgrader = websocket.Upgrader{
ReadBufferSize: 4096,
WriteBufferSize: 4096,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
var (
newline = []byte{'\n'}
space = []byte{' '}
)
type CometClient struct {
hub *CometHub
conn *websocket.Conn
send chan []byte
receive chan []byte
bizId string
bizType string
channelId string
page string
closeChan chan struct{}
adminMonitorCloseChan chan struct{}
msgHandleCloseChan chan struct{}
pingFailCount int
sendFailCount int
}
func newCometClient(_hub *CometHub, _conn *websocket.Conn, msgChanSize int, _bizId, _bizType, channelId, page string) *CometClient {
return &CometClient{
hub: _hub,
conn: _conn,
bizId: _bizId,
bizType: _bizType,
channelId: channelId,
page: page,
send: make(chan []byte, msgChanSize),
receive: make(chan []byte, msgChanSize),
closeChan: make(chan struct{}),
adminMonitorCloseChan: make(chan struct{}),
msgHandleCloseChan: make(chan struct{}),
pingFailCount: 0,
sendFailCount: 0,
}
}
func (client *CometClient) Close() {
for {
select {
case <-client.closeChan:
client.conn.Close()
}
}
}
func (client *CometClient) Receive() {
defer func() {
fmt.Println("receive client close")
client.conn.Close()
client.hub.unregister <- client
client.adminMonitorCloseChan <- struct{}{}
client.msgHandleCloseChan <- struct{}{}
if err := recover(); err != nil {
}
}()
client.conn.SetReadLimit(maxMessageSize)
//client.conn.SetReadDeadline(time.Now().Add(pongWait))
client.conn.SetReadDeadline(time.Now().Add(readTimeout))
//client.conn.SetReadDeadline(time.Time{})
//client.conn.SetPongHandler(func(string) error { client.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
client.conn.SetPongHandler(func(string) error { client.conn.SetReadDeadline(time.Now().Add(readTimeout)); return nil })
for {
_, message, err := client.conn.ReadMessage()
fmt.Printf("[%v]: receiving message: %s\n", time.Now(), string(message))
if err != nil {
fmt.Printf("socket read err is %+v\n", err)
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
fmt.Printf("error: %v\n", err)
}
break
}
message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
client.receive <- message
}
}
func (client *CometClient) Send() {
ticker := time.NewTicker(pingPeriod)
defer func() {
fmt.Println("send client close")
ticker.Stop()
client.conn.Close()
client.msgHandleCloseChan <- struct{}{}
if err := recover(); err != nil {
}
}()
for {
select {
case message, ok := <-client.send:
fmt.Printf("message sent to client: page %s, channelId: %s, clientId %s\n", client.page, client.channelId, client.bizId)
fmt.Printf("message sent to client is %s\n", string(message))
//if string(message) != "" {
client.conn.SetWriteDeadline(time.Now().Add(writeWait))
if !ok {
// The hub closed the channel.
client.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
w, err := client.conn.NextWriter(websocket.TextMessage)
if err != nil {
fmt.Printf("Could not get the socket writer with error:%+v\n", err)
return
}
w.Write(message)
if err := w.Close(); err != nil {
//client.sendFailCount += 1
//if client.sendFailCount > 10 {
return
//}
}
//}
case <-ticker.C:
fmt.Printf("constantly send ping message to client: %+v\n", *client)
client.conn.SetWriteDeadline(time.Now().Add(writeWait))
//if err := client.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
if err := client.conn.WriteMessage(websocket.TextMessage, []byte(`{"act": "test"}`)); err != nil {
fmt.Printf("failed to send the socket ping message, client is %+v\n", *client)
//client.pingFailCount += 1
//if client.pingFailCount > 10 {
// return
//}
return
}
}
}
}
func serveWS(hub *CometHub, w http.ResponseWriter, r *http.Request) {
fmt.Printf("new connection is coming\n")
clientId := r.URL.Query().Get("clientId")
clientType := r.URL.Query().Get("clientType")
channelId := r.URL.Query().Get("channelId")
page := r.URL.Query().Get("page")
if clientId == "" && clientType == "" {
return
}
conn, err := wsupgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Printf("Failed to set websocket upgrade: %+v\n", err)
return
}
client := newCometClient(hub, conn, 1024, clientId, clientType, channelId, page)
fmt.Println("prepare to register the client")
client.hub.register <- client
fmt.Println("finish to register the client")
go client.Send()
go client.Close()
client.Receive()
}