forked from zhaojh329/rttys
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
148 lines (120 loc) · 2.33 KB
/
user.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
package main
import (
"fmt"
"net/http"
"sync/atomic"
"time"
"rttys/client"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/rs/zerolog/log"
)
const (
loginErrorNone = 0x00
loginErrorOffline = 0x01
loginErrorBusy = 0x02
)
type user struct {
br *broker
sid string
devid string
conn *websocket.Conn
closed uint32
send chan *usrMessage // Buffered channel of outbound messages.
}
type usrMessage struct {
sid string
typ int
data []byte
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func (u *user) IsDevice() bool {
return false
}
func (u *user) DeviceID() string {
return u.devid
}
func (u *user) WriteMsg(typ int, data []byte) {
u.send <- &usrMessage{
typ: typ,
data: data,
}
}
func (u *user) Closed() bool {
return atomic.LoadUint32(&u.closed) == 1
}
func (u *user) Close() {
if u.Closed() {
return
}
atomic.StoreUint32(&u.closed, 1)
u.conn.Close()
close(u.send)
}
func userLoginAck(code int, c client.Client) {
msg := fmt.Sprintf(`{"type":"login","sid":"%s","err":%d}`, c.(*user).sid, code)
c.WriteMsg(websocket.TextMessage, []byte(msg))
}
func (u *user) readLoop() {
defer func() {
u.br.unregister <- u
}()
for {
typ, data, err := u.conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Error().Msg(err.Error())
}
break
}
u.br.userMessage <- &usrMessage{u.sid, typ, data}
}
}
func (u *user) writeLoop() {
ticker := time.NewTicker(time.Second * 5)
defer func() {
ticker.Stop()
u.br.unregister <- u
}()
for {
select {
case <-ticker.C:
u.WriteMsg(websocket.PingMessage, []byte{})
case msg, ok := <-u.send:
if !ok {
return
}
err := u.conn.WriteMessage(msg.typ, msg.data)
if err != nil {
log.Error().Msg(err.Error())
return
}
}
}
}
func serveUser(br *broker, c *gin.Context) {
devid := c.Param("devid")
if devid == "" {
c.Status(http.StatusBadRequest)
return
}
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
c.Status(http.StatusBadRequest)
log.Error().Msg(err.Error())
return
}
u := &user{
br: br,
conn: conn,
devid: devid,
send: make(chan *usrMessage, 256),
}
go u.readLoop()
go u.writeLoop()
br.register <- u
}