-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket.go
65 lines (58 loc) · 1.5 KB
/
websocket.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
package main
import (
"encoding/json"
"time"
ws "github.com/dictor/wswrapper"
"github.com/sirupsen/logrus"
)
type (
generalMessage struct {
Type string `json:"type"`
Data interface{} `json:"data"`
}
)
func wsEvent(evt *ws.WebsocketEvent) {
switch evt.Kind {
case ws.EVENT_RECIEVE:
//when some message received.
case ws.EVENT_REGISTER:
globalLogger.WithFields(logrus.Fields{
"id": evt.Client.Id(),
"remote_address": evt.Client.Connection().RemoteAddr().String(),
"local_address": evt.Client.Connection().LocalAddr().String(),
}).Info("websocker client registered")
case ws.EVENT_UNREGISTER:
globalLogger.WithFields(logrus.Fields{
"id": evt.Client.Id(),
"remote_address": evt.Client.Connection().RemoteAddr().String(),
"local_address": evt.Client.Connection().LocalAddr().String(),
}).Info("websocker client unregistered")
case ws.EVENT_ERROR:
globalLogger.WithField("error", evt.Err).Errorln("websocket error")
}
}
func broadcastData(h *ws.WebsocketHub, sendQueue chan []byte, interval int) {
defer ValueMutex.Unlock()
for {
ValueMutex.Lock()
data, err := json.Marshal(generalMessage{
Type: "value",
Data: Value,
})
ValueMutex.Unlock()
if err != nil {
globalLogger.WithField("error", err).Errorln("error caused while value broadcast")
}
h.SendAll(data)
emptyLoop:
for {
select {
case q := <-sendQueue:
h.SendAll(q)
default:
break emptyLoop
}
}
time.Sleep(time.Millisecond * time.Duration(interval))
}
}