forked from zhaojh329/rttys
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
186 lines (161 loc) · 4.33 KB
/
client.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
/*
* Copyright (C) 2017 Jianhui Zhao <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package main
import (
"log"
"time"
"sync"
"errors"
"net/http"
"github.com/gorilla/websocket"
)
const (
// Time allowed to read the next pong message from the peer.
pongWait = 3 * time.Second
// pings to peer with this period.
pingPeriod = 5 * time.Second
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
type wsMessage struct {
msgType int
data []byte
c *Client
}
// Representing a device or user browser
type Client struct {
br *Bridge
isDev bool
// device description
description string
devid string
// Registration time
timestamp int64
sid string
conn *websocket.Conn
// Buffered channel of outbound messages.
outbound chan *wsMessage
cmdid uint32
cmd map[uint32]chan *wsMessage
// Avoid repeated closes and concurrent map writes
mutex sync.Mutex
isClosed bool
closeChan chan byte
}
func (c *Client) wsClose() {
defer c.mutex.Unlock()
c.mutex.Lock()
if !c.isClosed {
c.conn.Close()
c.isClosed = true
close(c.closeChan)
}
}
func (c *Client) unregister() {
c.br.unregister <- c
}
func (c *Client) wsWrite(messageType int, data []byte) error {
select {
case c.outbound <- &wsMessage{messageType, data, c}:
case <- c.closeChan:
return errors.New("websocket closed")
}
return nil
}
func (c *Client) readPump() {
defer func() {
c.unregister()
}()
c.conn.SetPongHandler(func(string) error {
/* Set not time out */
c.conn.SetReadDeadline(time.Time{});
return nil
})
for {
msgType, data, err := c.conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("error: %v", err)
}
break
}
msg := &wsMessage{msgType, data, c}
select {
case c.br.inbound <- msg:
case <- c.closeChan:
return
}
}
}
func (c *Client) writePump() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
c.unregister()
}()
for {
select {
case msg := <- c.outbound:
if err := c.conn.WriteMessage(msg.msgType, msg.data); err != nil {
return
}
case <- ticker.C:
c.conn.SetReadDeadline(time.Now().Add(pongWait));
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
case <- c.closeChan:
return
}
}
}
/* serveWs handles websocket requests from the peer. */
func serveWs(br *Bridge, w http.ResponseWriter, r *http.Request) {
devid := r.URL.Query().Get("devid")
if devid == "" {
log.Println("devid required")
return
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
client := &Client{
br: br,
devid: devid,
conn: conn,
timestamp: time.Now().Unix(),
outbound: make(chan *wsMessage, 100),
closeChan: make(chan byte),
isClosed: false,
}
isDev := r.URL.Query().Get("device")
if isDev == "1" {
client.isDev = true
client.description = r.URL.Query().Get("description")
client.cmd = make(map[uint32]chan *wsMessage)
}
client.br.register <- client
go client.readPump()
go client.writePump()
}