This repository has been archived by the owner on Nov 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
sys.go
74 lines (62 loc) · 1.77 KB
/
sys.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
package server
import (
"fmt"
log "github.com/cihub/seelog"
"github.com/surgemq/message"
)
const (
ONCONENCTED = "$SYS/brokers/clients/connected/"
ONDISCONENCTED = "$SYS/brokers/clients/disconnected/"
)
func NewSYSMessage(topic, playload []byte) *message.PublishMessage {
infoMsg := message.NewPublishMessage()
infoMsg.SetTopic(topic)
infoMsg.SetPayload(playload)
infoMsg.SetQoS(0)
infoMsg.SetRetain(false)
return infoMsg
}
func (s *Server) PublishOnConnectedMessage(ip, username, clientID string) {
onConnect := []byte(fmt.Sprintf(`{"ipaddress":"%s","username":"%s","clientID":"%s"}`, ip, username, clientID))
topic := []byte(ONCONENCTED + clientID)
msg := NewSYSMessage(topic, onConnect)
s.PublishMessage(msg)
}
func (s *Server) PublishOnDisconnectedMessage(username, clientID string) {
onConnect := []byte(fmt.Sprintf(`{"username":"%s","clientID":"%s"}`, username, clientID))
topic := []byte(ONDISCONENCTED + clientID)
msg := NewSYSMessage(topic, onConnect)
s.PublishMessage(msg)
}
func (s *Server) PublishMessage(msg *message.PublishMessage) {
topic := string(msg.Topic())
r := s.sl.Match(topic)
// log.Info("psubs num: ", len(r.psubs))
if len(r.qsubs) == 0 && len(r.psubs) == 0 {
return
}
for _, sub := range r.psubs {
s.startGoRoutine(func() {
if sub != nil {
err := sub.client.writeMessage(msg)
if err != nil {
log.Error("process message for psub error, ", err)
}
}
})
}
for i, sub := range r.qsubs {
s.qmu.Lock()
if cnt, exist := s.queues[string(sub.topic)]; exist && i == cnt {
if sub != nil {
err := sub.client.writeMessage(msg)
if err != nil {
log.Error("process will message for qsub error, ", err)
}
}
s.queues[topic] = (s.queues[topic] + 1) % len(r.qsubs)
break
}
s.qmu.Unlock()
}
}