forked from davidfowl/signalr-ports
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hublifetimemanager.go
70 lines (60 loc) · 2.41 KB
/
hublifetimemanager.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
package signalr
import (
"sync"
)
// HubLifetimeManager is a lifetime manager abstraction for hub instances
// OnConnected() is called when a connection is started
// OnDisconnected() is called when a connection is finished
// InvokeAll() sends an invocation message to all hub connections
// InvokeClient() sends an invocation message to a specified hub connection
// InvokeGroup() sends an invocation message to a specified group of hub connections
// AddToGroup() adds a connection to the specified group
// RemoveFromGroup() removes a connection from the specified group
type HubLifetimeManager interface {
OnConnected(conn hubConnection)
OnDisconnected(conn hubConnection)
InvokeAll(target string, args []interface{})
InvokeClient(connectionID string, target string, args []interface{})
InvokeGroup(groupName string, target string, args []interface{})
AddToGroup(groupName, connectionID string)
RemoveFromGroup(groupName, connectionID string)
}
type defaultHubLifetimeManager struct {
clients sync.Map
groups sync.Map
}
func (d *defaultHubLifetimeManager) OnConnected(conn hubConnection) {
d.clients.Store(conn.GetConnectionID(), conn)
}
func (d *defaultHubLifetimeManager) OnDisconnected(conn hubConnection) {
d.clients.Delete(conn.GetConnectionID())
}
func (d *defaultHubLifetimeManager) InvokeAll(target string, args []interface{}) {
d.clients.Range(func(key, value interface{}) bool {
value.(hubConnection).SendInvocation(target, args)
return true
})
}
func (d *defaultHubLifetimeManager) InvokeClient(connectionID string, target string, args []interface{}) {
if client, ok := d.clients.Load(connectionID); ok {
client.(hubConnection).SendInvocation(target, args)
}
}
func (d *defaultHubLifetimeManager) InvokeGroup(groupName string, target string, args []interface{}) {
if groups, ok := d.groups.Load(groupName); ok {
for _, v := range groups.(map[string]hubConnection) {
v.SendInvocation(target, args)
}
}
}
func (d *defaultHubLifetimeManager) AddToGroup(groupName string, connectionID string) {
if client, ok := d.clients.Load(connectionID); ok {
groups, _ := d.groups.LoadOrStore(groupName, make(map[string]hubConnection))
groups.(map[string]hubConnection)[connectionID] = client.(hubConnection)
}
}
func (d *defaultHubLifetimeManager) RemoveFromGroup(groupName string, connectionID string) {
if groups, ok := d.groups.Load(groupName); ok {
delete(groups.(map[string]hubConnection), connectionID)
}
}