-
Notifications
You must be signed in to change notification settings - Fork 12
/
channel.go
238 lines (201 loc) · 5 KB
/
channel.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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package shadiaosocketio
import (
"errors"
"github.com/Baiguoshuai1/shadiaosocketio/protocol"
"github.com/Baiguoshuai1/shadiaosocketio/utils"
"github.com/Baiguoshuai1/shadiaosocketio/websocket"
"net"
"net/http"
"sync"
"time"
)
const (
queueBufferSize = 10000
)
const (
DefaultCloseTxt = "transport close"
DefaultCloseCode = 101
)
var (
ErrorWrongHeader = errors.New("Wrong header")
)
/*
*
engine.io header to send or receive
*/
type Header struct {
Sid string `json:"sid"`
Upgrades []string `json:"upgrades"`
PingInterval int `json:"pingInterval"`
PingTimeout int `json:"pingTimeout"`
}
/*
*
socket.io connection handler
use IsAlive to check that handler is still working
use Dial to connect to websocket
use In and Out channels for message exchange
Close message means channel is closed
ping is automatic
*/
type Channel struct {
conn *websocket.Connection
out chan interface{}
header Header
alive bool
aliveLock sync.Mutex
ack ackProcessor
server *Server
ip string
request *http.Request
}
func (c *Channel) BinaryMessage() bool {
return c.conn.GetUseBinaryMessage()
}
func (c *Channel) RemoteAddr() net.Addr {
return c.conn.RemoteAddr()
}
func (c *Channel) LocalAddr() net.Addr {
return c.conn.LocalAddr()
}
func (c *Channel) initChannel() {
//TODO: queueBufferSize from constant to server or socket variable
c.out = make(chan interface{}, queueBufferSize)
//c.ack.resultWaiters = make(map[int](chan string))
c.setAliveValue(true)
}
func (c *Channel) Id() string {
return c.header.Sid
}
func (c *Channel) ReadBytes() int {
return c.conn.GetReadBytes()
}
func (c *Channel) WriteBytes() int {
return c.conn.GetWriteBytes()
}
/*
*
Checks that Channel is still alive
*/
func (c *Channel) IsAlive() bool {
c.aliveLock.Lock()
isAlive := c.alive
c.aliveLock.Unlock()
return isAlive
}
func (c *Channel) setAliveValue(value bool) {
c.aliveLock.Lock()
c.alive = value
c.aliveLock.Unlock()
}
/*
*
Close channel
*/
func closeChannel(c *Channel, m *methods, args ...interface{}) error {
if !c.IsAlive() {
//already closed
return nil
}
c.setAliveValue(false)
var s []interface{}
closeErr := &websocket.CloseError{}
if len(args) == 0 {
closeErr.Code = DefaultCloseCode
closeErr.Text = DefaultCloseTxt
s = append(s, closeErr)
} else {
s = append(s, args...)
}
c.conn.Close()
c.out <- protocol.CloseMsg
m.callLoopEvent(c, OnDisconnection, s...)
return nil
}
// incoming messages loop, puts incoming messages to In channel
func inLoop(c *Channel, m *methods) error {
for {
msg, err := c.conn.GetMessage()
if err != nil {
return closeChannel(c, m, err)
}
prefix := string(msg[0])
protocolV := c.conn.GetProtocol()
switch prefix {
case protocol.OpenMsg:
if err := utils.Json.UnmarshalFromString(msg[1:], &c.header); err != nil {
closeErr := &websocket.CloseError{}
closeErr.Code = websocket.ParseOpenMsgCode
closeErr.Text = err.Error()
return closeChannel(c, m, closeErr)
}
if protocolV == protocol.Protocol3 {
m.callLoopEvent(c, OnConnection)
// in protocol v3, the client sends a ping, and the server answers with a pong
go SchedulePing(c)
}
if c.conn.GetProtocol() == protocol.Protocol4 {
// in protocol v4 & binary msg Connection to a namespace
if c.conn.GetUseBinaryMessage() {
c.out <- &protocol.MsgPack{
Type: protocol.CONNECT,
Nsp: protocol.DefaultNsp,
Data: &struct {
}{},
}
// in protocol v4 & text msg Connection to a namespace
} else {
c.out <- protocol.CommonMsg + protocol.OpenMsg
}
}
case protocol.CloseMsg:
return closeChannel(c, m)
case protocol.PingMsg:
// in protocol v4, the server sends a ping, and the client answers with a pong
c.out <- protocol.PongMsg
case protocol.PongMsg:
case protocol.UpgradeMsg:
case protocol.CommonMsg:
// in protocol v3 & binary msg ps: 4{"type":0,"data":null,"nsp":"/","id":0}
// in protocol v3 & text msg ps: 40 or 41 or 42["message", ...]
// in protocol v4 & text msg ps: 40 or 41 or 42["message", ...]
go m.processIncomingMessage(c, msg[1:])
default:
// in protocol v4 & binary msg ps: {"type":0,"data":{"sid":"HWEr440000:1:R1CHyink:shadiao:101"},"nsp":"/","id":0}
go m.processIncomingMessage(c, msg)
}
}
}
func outLoop(c *Channel, m *methods) error {
for {
outBufferLen := len(c.out)
if outBufferLen >= queueBufferSize-1 {
closeErr := &websocket.CloseError{}
closeErr.Code = websocket.QueueBufferSizeCode
closeErr.Text = ErrorSocketOverflood.Error()
closeChannel(c, m, closeErr)
}
msg := <-c.out
if msg == protocol.CloseMsg {
return nil
}
err := c.conn.WriteMessage(msg)
if err != nil {
closeErr := &websocket.CloseError{}
closeErr.Code = websocket.WriteBufferErrCode
closeErr.Text = err.Error()
closeChannel(c, m, closeErr)
}
}
}
func SchedulePing(c *Channel) {
interval, _ := c.conn.PingParams()
ticker := time.NewTicker(interval)
for {
<-ticker.C
if !c.IsAlive() {
return
}
c.out <- protocol.PingMsg
}
}