-
Notifications
You must be signed in to change notification settings - Fork 1
/
hub.go
52 lines (46 loc) · 969 Bytes
/
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
package main
type Hub struct {
clients map[string]*Client
rooms map[string]*Room
register chan struct {
roomID string
client *Client
}
unregister chan string
}
func newHub() *Hub {
return &Hub{
clients: make(map[string]*Client),
rooms: make(map[string]*Room),
register: make(chan struct {
roomID string
client *Client
}),
unregister: make(chan string),
}
}
// run: run async
func (hub *Hub) run() {
for {
select {
case reg := <-hub.register:
room, ok := hub.rooms[reg.roomID]
if !ok {
room = newRoom(reg.roomID)
room.unregisterToHubCh = hub.unregister
go room.run()
hub.rooms[reg.roomID] = room
}
// if more than two clients connect, close them all
if len(room.clients) == 2 {
reg.client.close()
room.unregisterCh <- struct{}{}
continue
}
room.registerCh <- reg.client
case id := <-hub.unregister:
delete(hub.rooms, id)
// fmt.Printf("Room %s removed\n", id)
}
}
}