-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
87 lines (73 loc) · 1.34 KB
/
client.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
package sseio
import (
"sync"
"time"
)
const pingEvent = "ping"
type message struct {
event string
data interface{}
}
type roomInfo struct {
id string
event string
}
type client struct {
id string
dying bool
messageChan chan *message
channelLock sync.RWMutex
rooms []*roomInfo
heartbeatTimer *time.Timer
}
func newClient(id string, messageChan chan *message) *client {
c := &client{
id: id,
messageChan: messageChan,
}
c.startHeartbeat()
return c
}
func (c *client) getId() string {
return c.id
}
func (c *client) close() {
c.channelLock.Lock()
defer c.channelLock.Unlock()
if !c.dying {
c.dying = true
close(c.messageChan)
}
}
func (c *client) isDying() bool {
return c.dying == true
}
func (c *client) sendMessage(event string, data interface{}) {
if data != nil {
c.channelLock.RLock()
defer c.channelLock.RUnlock()
if !c.dying {
c.messageChan <- &message{event: event, data: data}
}
}
}
func (c *client) addRoom(event string, roomId string) {
c.rooms = append(c.rooms, &roomInfo{
id: roomId,
event: event,
})
}
func (c *client) getRooms() []*roomInfo {
return c.rooms
}
func (c *client) startHeartbeat() {
go func() {
timer := time.NewTicker(3 * time.Second)
for {
select {
case <-timer.C:
c.sendMessage(pingEvent, nil)
}
}
}()
}