-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
channel.go
73 lines (60 loc) · 1.3 KB
/
channel.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
package sse
import (
"sync"
)
// Channel represents a server sent events channel.
type Channel struct {
mu sync.RWMutex
lastEventID string
name string
clients map[*Client]bool
}
func newChannel(name string) *Channel {
return &Channel{
sync.RWMutex{},
"",
name,
make(map[*Client]bool),
}
}
// SendMessage broadcast a message to all clients in a channel.
func (c *Channel) SendMessage(message *Message) {
c.lastEventID = message.id
c.mu.RLock()
for c, open := range c.clients {
if open {
c.send <- message
}
}
c.mu.RUnlock()
}
// Close closes the channel and disconnect all clients.
func (c *Channel) Close() {
// Kick all clients of this channel.
for client := range c.clients {
c.removeClient(client)
}
}
// ClientCount returns the number of clients connected to this channel.
func (c *Channel) ClientCount() int {
c.mu.RLock()
count := len(c.clients)
c.mu.RUnlock()
return count
}
// LastEventID returns the ID of the last message sent.
func (c *Channel) LastEventID() string {
return c.lastEventID
}
func (c *Channel) addClient(client *Client) {
c.mu.Lock()
c.clients[client] = true
c.mu.Unlock()
}
func (c *Channel) removeClient(client *Client) {
c.mu.Lock()
c.clients[client] = false
delete(c.clients, client)
c.mu.Unlock()
close(client.send)
}