-
Notifications
You must be signed in to change notification settings - Fork 0
/
hub.go
100 lines (83 loc) · 2.15 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
98
99
100
package main
import (
"fmt"
"log"
"encoding/json"
)
// hub maintains the set of active clients and broadcasts messages to the
// clients.
type Hub struct {
// Registered clients.
clients map[*Client]bool
channels map[string]*Channel
// Inbound messages from the clients.
broadcast chan Notification
// Register requests from the clients.
register chan *Client
// Unregister requests from clients.
unregister chan *Client
}
func newHub() *Hub {
return &Hub{
broadcast: make(chan Notification),
register: make(chan *Client),
unregister: make(chan *Client),
channels: make(map[string]*Channel),
clients: make(map[*Client]bool),
}
}
func (hub *Hub) run() {
for {
select {
case client := <-hub.register:
hub.clients[client] = true
case client := <-hub.unregister:
if _, ok := hub.clients[client]; ok {
hub.deleteClient(client)
}
case notification := <-hub.broadcast:
fmt.Println(string(notification.Content), len(hub.clients))
hub.dealWithNotification(¬ification)
}
}
}
func (hub *Hub) addToChannel(chanName string, client *Client) {
channel, ok := hub.channels[chanName]
if !ok {
hub.newChannel(chanName)
}
channel.AddClient(client)
}
func (hub *Hub) newChannel(name string) *Channel {
channel := NewChannel(hub, name)
hub.channels[name] = channel
return channel
}
func (hub *Hub) terminateChannel(name string) {
delete(hub.channels, name)
}
func (hub *Hub) deleteClient(client *Client) {
var leaveNotification LeaveNotification
leaveNotification.Type = "leaveChannel"
leaveNotification.Data.User = client.Username
for channelName := range client.Channels {
if channel, ok := hub.channels[channelName]; ok {
channel.DeleteClient(client)
leaveNotification.Data.ChannelName = channelName
bytes, err := json.Marshal(channelName)
if err != nil {
panic(err)
}
channel.BroadcastBytes(bytes)
}
}
close(client.send)
delete(hub.clients, client)
}
func (hub *Hub) broadcastOnChannel(channelName string, notification *Notification) {
if channel, ok := hub.channels[channelName]; ok {
channel.Broadcast(notification)
} else {
log.Printf("Channel: %s doesn't exist\n", channelName)
}
}