forked from zhaojh329/rttys
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
123 lines (98 loc) · 2.15 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
package main
import (
"github.com/gorilla/websocket"
log "github.com/sirupsen/logrus"
"net/http"
"strconv"
"sync"
"time"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
type Client struct {
br *Broker
ws *websocket.Conn
devid string
mutex sync.Mutex /* Avoid repeated closes */
closed bool
closeChan chan byte
outMessage chan *wsOutMessage /* Buffered channel of outbound messages */
}
type wsOutMessage struct {
msgType int
data []byte
}
func (c *Client) Close() {
defer c.mutex.Unlock()
c.mutex.Lock()
if !c.closed {
c.ws.Close()
c.closed = true
close(c.closeChan)
}
}
func (c *Client) wsWrite(msgType int, data []byte) {
c.outMessage <- &wsOutMessage{msgType, data}
}
func (c *Client) writePump() {
defer c.Close()
for {
select {
case msg := <-c.outMessage:
if err := c.ws.WriteMessage(msg.msgType, msg.data); err != nil {
return
}
case <-c.closeChan:
return
}
}
}
/* serveWs handles websocket requests from the device or user. */
func serveWs(br *Broker, w http.ResponseWriter, r *http.Request, cfg *RttysConfig) {
isDev := r.URL.Query().Get("device") != ""
if isDev {
token := r.Header.Get("Authorization")
if token != cfg.token {
log.Error("Invalid token from terminal device")
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
}
keepalive, _ := strconv.Atoi(r.URL.Query().Get("keepalive"))
devid := r.URL.Query().Get("devid")
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
if devid == "" {
conn.Close()
log.Error("devid required")
return
}
client := &Client{
br: br,
devid: devid,
ws: conn,
closeChan: make(chan byte),
outMessage: make(chan *wsOutMessage, 1000),
}
if isDev {
desc := r.URL.Query().Get("description")
sessions := make(map[uint8]string)
dev := &Device{client, desc, time.Now().Unix(), sessions}
if keepalive > 0 {
go dev.keepAlive(int64(keepalive))
}
go dev.readAlway()
br.connecting <- dev
} else {
user := &User{client, ""}
go user.readAlway()
br.logining <- user
}
go client.writePump()
}