-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathbroken_connections.go
95 lines (78 loc) · 1.87 KB
/
broken_connections.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
package server
import (
"time"
"github.com/sirupsen/logrus"
)
const DefaultCheckInterval = 300
//NewCheckBrokenConnections create a new CheckBrokenConnections
func NewCheckBrokenConnections(realm IRealm, opts Options, onClose func(client IClient)) *CheckBrokenConnections {
if onClose == nil {
onClose = func(client IClient) {}
}
return &CheckBrokenConnections{
realm: realm,
opts: opts,
onClose: onClose,
log: createLogger("checkBrokenConnections", opts),
close: make(chan bool, 1),
}
}
//CheckBrokenConnections watch for broken connections
type CheckBrokenConnections struct {
realm IRealm
opts Options
onClose func(IClient)
ticker *time.Ticker
log *logrus.Entry
close chan bool
}
func (b *CheckBrokenConnections) checkConnections() {
clientsIds := b.realm.GetClientsIds()
now := getTime()
aliveTimeout := b.opts.AliveTimeout
for _, clientID := range clientsIds {
client := b.realm.GetClientByID(clientID)
if client == nil {
continue
}
timeSinceLastPing := now - client.GetLastPing()
if timeSinceLastPing < aliveTimeout {
continue
}
socket := client.GetSocket()
if socket != nil {
b.log.Infof("Closing broken connection clientID=%s", clientID)
err := socket.Close()
if err != nil {
b.log.Warnf("Failed to close socket: %s", err)
}
}
b.realm.ClearMessageQueue(clientID)
b.realm.RemoveClientByID(clientID)
client.SetSocket(nil)
b.onClose(client)
}
}
//Stop close the connection checker
func (b *CheckBrokenConnections) Stop() {
if b.ticker == nil {
return
}
b.close <- true
}
//Start initialize the connection checker
func (b *CheckBrokenConnections) Start() {
b.ticker = time.NewTicker(DefaultCheckInterval * time.Millisecond)
go func() {
for {
select {
case <-b.close:
b.ticker.Stop()
b.ticker = nil
return
case <-b.ticker.C:
b.checkConnections()
}
}
}()
}