-
Notifications
You must be signed in to change notification settings - Fork 0
/
hub.go
97 lines (84 loc) · 1.74 KB
/
hub.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
package main
//import (
//"fmt"
//)
type Hub struct {
connections map[*Connection]bool
handle chan Message
register chan *Connection
unregister chan *Connection
}
func (h *Hub) Offline(conn *Connection) {
if _, ok := h.connections[conn]; ok {
if s := conn.channel; s != nil {
s.Del(conn)
}
delete(h.connections, conn)
close(conn.send)
}
}
func (h *Hub) Online(conn *Connection) {
h.connections[conn] = true
}
type Channel struct {
conns map[*Connection]bool
}
func (s *Channel) Add(conn *Connection) {
s.conns[conn] = true
conn.channel = s
}
func (s *Channel) Del(conn *Connection) {
delete(s.conns, conn)
}
type ChannelList struct {
channels map[string]*Channel
}
func (sl *ChannelList) GetChannel(key string) *Channel {
if _, ok := sl.channels[key]; !ok {
sl.channels[key] = &Channel{conns: make(map[*Connection]bool)}
}
return sl.channels[key]
}
func (sl *ChannelList) GC() {
for i := range sl.channels {
if len(sl.channels[i].conns) == 0 {
delete(sl.channels, i)
}
}
}
var channellist = ChannelList{
channels: make(map[string]*Channel),
}
var hub = Hub{
connections: make(map[*Connection]bool),
handle: make(chan Message),
register: make(chan *Connection),
unregister: make(chan *Connection),
}
func (h *Hub) run() {
for {
select {
case c := <-hub.register:
hub.Online(c)
channel := channellist.GetChannel(c.chname)
channel.Add(c)
case c := <-hub.unregister:
hub.Offline(c)
channellist.GC()
case m := <-hub.handle:
channel := m.conn.channel
for c := range channel.conns {
if c == m.conn {
continue
}
select {
case c.send <- m.msg:
default:
hub.Offline(c)
channellist.GC()
}
}
}
//fmt.Println(channellist.GetChannel("test"))
}
}