forked from googollee/go-socket.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection_handlers.go
121 lines (96 loc) · 2.43 KB
/
connection_handlers.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
package socketio
import (
"log"
"github.com/googollee/go-socket.io/parser"
)
var readHandlerMapping = map[parser.Type]readHandler{
parser.Ack: ackPacketHandler,
parser.Connect: connectPacketHandler,
parser.Disconnect: disconnectPacketHandler,
}
func ackPacketHandler(c *conn, header parser.Header) error {
conn, ok := c.namespaces.Get(header.Namespace)
if !ok {
_ = c.decoder.DiscardLast()
return nil
}
conn.dispatch(header)
return nil
}
func eventPacketHandler(c *conn, event string, header parser.Header) error {
conn, ok := c.namespaces.Get(header.Namespace)
if !ok {
_ = c.decoder.DiscardLast()
return nil
}
handler, ok := c.handlers.Get(header.Namespace)
if !ok {
_ = c.decoder.DiscardLast()
return nil
}
args, err := c.decoder.DecodeArgs(handler.getEventTypes(event))
if err != nil {
c.onError(header.Namespace, err)
return errDecodeArgs
}
ret, err := handler.dispatchEvent(conn, event, args...)
if err != nil {
c.onError(header.Namespace, err)
return errHandleDispatch
}
if len(ret) > 0 {
header.Type = parser.Ack
c.write(header, ret...)
}
return nil
}
func connectPacketHandler(c *conn, header parser.Header) error {
if err := c.decoder.DiscardLast(); err != nil {
c.onError(header.Namespace, err)
return nil
}
handler, ok := c.handlers.Get(header.Namespace)
if !ok {
c.onError(header.Namespace, errFailedConnectNamespace)
return errFailedConnectNamespace
}
conn, ok := c.namespaces.Get(header.Namespace)
if !ok {
conn = newNamespaceConn(c, header.Namespace, handler.broadcast)
c.namespaces.Set(header.Namespace, conn)
conn.Join(c.ID())
}
_, err := handler.dispatch(conn, header)
if err != nil {
log.Println("dispatch connect packet", err)
c.onError(header.Namespace, err)
return errHandleDispatch
}
c.write(header)
return nil
}
func disconnectPacketHandler(c *conn, header parser.Header) error {
args, err := c.decoder.DecodeArgs(defaultHeaderType)
if err != nil {
c.onError(header.Namespace, err)
return errDecodeArgs
}
conn, ok := c.namespaces.Get(header.Namespace)
if !ok {
_ = c.decoder.DiscardLast()
return nil
}
conn.LeaveAll()
c.namespaces.Delete(header.Namespace)
handler, ok := c.handlers.Get(header.Namespace)
if !ok {
return nil
}
_, err = handler.dispatch(conn, header, args...)
if err != nil {
log.Println("dispatch disconnect packet", err)
c.onError(header.Namespace, err)
return errHandleDispatch
}
return nil
}