-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgows.go
More file actions
216 lines (164 loc) · 4.34 KB
/
gows.go
File metadata and controls
216 lines (164 loc) · 4.34 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
200
201
202
203
204
205
206
207
208
209
package gows
import (
"errors"
"github.com/gorilla/websocket"
"net/http"
"sync"
"time"
)
//default gows Upgrader
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
EnableCompression: true,
}
//Initialization new Hub
func Init() *Hub {
//new channels map
channelsMap:=make(map[string]connections)
hub:=&Hub{channels:channelsMap,channelsLock: &sync.Mutex{}}
//set gows default settings
hub.SetDefault()
return hub
}
//default settings
func (h *Hub) SetDefault() {
h.WriteWait = 10 * time.Second
h.PongWait= 15 * time.Second
h.PingPeriod = (h.PongWait * 9) / 10
h.MaxMessageSize = 1024
h.Upgrader = &upgrader
}
//add new connection to hub for channel
func (h *Hub) addConnection(channelId string,con *websocket.Conn) *Connection {
//check if channel exists in hub
_, ok := h.channels[channelId]
//generate new connection id
connId:=Uuid()
//new connection
connection:=Connection{
lock: &sync.Mutex{},
socket: con,
Channel: channelId,
ConnId: connId,
}
//lock hub channels
h.channelsLock.Lock()
//unlock hub channels
defer func() {
h.channelsLock.Unlock()
}()
//if channel exists
if ok{
//write new connection to map
h.channels[channelId].connections[connId]=connection
}else{
newConnections:=make(map[string]Connection)
newConnections[connId] = connection
h.channels[channelId]=connections{
connections:newConnections,
}
}
return &connection
}
func (h *Hub) RemoveConn(c *Connection) {
conn,check :=h.checkConnection(c)
if check{
//close socket
conn.socket.Close()
//remove connection
delete(h.channels[conn.Channel].connections, conn.ConnId)
if len(h.channels[conn.Channel].connections) == 0{
delete(h.channels,conn.Channel)
}
}
}
func (h *Hub) checkConnection(c *Connection) (*Connection,bool) {
conn,ok:=h.channels[c.Channel].connections[c.ConnId]
return &conn,ok
}
func (h *Hub) Open(channel string, res http.ResponseWriter, req *http.Request) (*Connection,error) {
//upgrade current request with hub Upgrader in safe lock
var conn, err = h.Upgrader.Upgrade(res, req, nil)
if err!=nil{
return &Connection{},err
}
//add channel connection to hub in safe lock
connection:=h.addConnection(channel,conn)
//return connection
return connection,nil
}
func (h *Hub) Listen(c *Connection,messageHandler func(messageType int, message []byte )) error {
//check connection still in hub
conn,check:=h.checkConnection(c)
if !check{
return errors.New("error connection not found in hub")
}
//open thread for reading messages from connection
go h.readMessages(conn,messageHandler)
//send ping messages
h.pingHandler(conn)
//listen ended
return errors.New("socket connection ended")
}
func (h *Hub) WriteOnChannel(channel string,message []byte){
for _,connection:= range h.channels[channel].connections{
h.writeToConn(&connection,1,message)
}
}
func (h *Hub) WriteOnConn(c *Connection,messageType int, message []byte) error {
conn,check:=h.checkConnection(c)
if !check{
return errors.New("error connection not found in hub")
}
return h.writeToConn(conn,messageType,message)
}
func (h *Hub) writeToConn(c *Connection,messageType int, message []byte) error {
//lock connection
c.lock.Lock()
defer func() {
//unlock connection
c.lock.Unlock()
}()
c.socket.SetWriteDeadline(time.Now().Add(h.WriteWait))
err:=c.socket.WriteMessage(messageType,message)
if err != nil {
h.RemoveConn(c)
return err
}
return err
}
func (h *Hub) readMessages(Conn *Connection,messageHandler func(messageType int, message []byte )) {
defer func() {
h.RemoveConn(Conn)
}()
socket:=Conn.socket
socket.SetReadLimit(h.MaxMessageSize)
socket.SetReadDeadline(time.Now().Add(h.PongWait))
socket.SetPongHandler(func(string) error { socket.SetReadDeadline(time.Now().Add(h.PongWait)); return nil })
for {
messageType, message, err := socket.ReadMessage()
if err != nil {
return
}
messageHandler(messageType,message)
}
}
func (h *Hub) pingHandler(conn *Connection) {
socket:=conn.socket
ticker := time.NewTicker(h.PingPeriod)
defer func() {
h.RemoveConn(conn)
ticker.Stop()
}()
for {
select {
case <-ticker.C:
socket.SetWriteDeadline(time.Now().Add(h.WriteWait))
if err := socket.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
return
}
}
}
}