This repository has been archived by the owner on Sep 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 840
/
namespace_conn.go
107 lines (82 loc) · 2.09 KB
/
namespace_conn.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
package socketio
import (
"reflect"
"sync"
"github.com/googollee/go-socket.io/parser"
)
// Namespace describes a communication channel that allows you to split the logic of your application
// over a single shared connection.
type Namespace interface {
// Context of this connection. You can save one context for one
// connection, and share it between all handlers. The handlers
// are called in one goroutine, so no need to lock context if it
// only accessed in one connection.
Context() interface{}
SetContext(ctx interface{})
Namespace() string
Emit(eventName string, v ...interface{})
Join(room string)
Leave(room string)
LeaveAll()
Rooms() []string
}
type namespaceConn struct {
*conn
broadcast Broadcast
namespace string
context interface{}
ack sync.Map
}
func newNamespaceConn(conn *conn, namespace string, broadcast Broadcast) *namespaceConn {
return &namespaceConn{
conn: conn,
namespace: namespace,
broadcast: broadcast,
}
}
func (nc *namespaceConn) SetContext(ctx interface{}) {
nc.context = ctx
}
func (nc *namespaceConn) Context() interface{} {
return nc.context
}
func (nc *namespaceConn) Namespace() string {
return nc.namespace
}
func (nc *namespaceConn) Emit(eventName string, v ...interface{}) {
header := parser.Header{
Type: parser.Event,
}
if nc.namespace != aliasRootNamespace {
header.Namespace = nc.namespace
}
if l := len(v); l > 0 {
last := v[l-1]
lastV := reflect.TypeOf(last)
if lastV.Kind() == reflect.Func {
f := newAckFunc(last)
header.ID = nc.conn.nextID()
header.NeedAck = true
nc.ack.Store(header.ID, f)
v = v[:l-1]
}
}
args := make([]reflect.Value, len(v)+1)
args[0] = reflect.ValueOf(eventName)
for i := 1; i < len(args); i++ {
args[i] = reflect.ValueOf(v[i-1])
}
nc.conn.write(header, args...)
}
func (nc *namespaceConn) Join(room string) {
nc.broadcast.Join(room, nc)
}
func (nc *namespaceConn) Leave(room string) {
nc.broadcast.Leave(room, nc)
}
func (nc *namespaceConn) LeaveAll() {
nc.broadcast.LeaveAll(nc)
}
func (nc *namespaceConn) Rooms() []string {
return nc.broadcast.Rooms(nc)
}