-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathagent_status_ws.go
More file actions
executable file
·104 lines (88 loc) · 2.32 KB
/
agent_status_ws.go
File metadata and controls
executable file
·104 lines (88 loc) · 2.32 KB
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
96
97
98
99
100
101
102
103
104
package main
import (
"fmt"
"time"
"log"
"net/http"
"sync"
//"encoding/json"
"github.com/gorilla/websocket"
"github.com/satori/go.uuid"
)
var clientMutex = &sync.Mutex{}
var clientMAP map[string]*WallboardWS = make(map[string]*WallboardWS)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
const (
// Time allowed to write a message to the peer.
writeWait = time.Second
)
type WallboardWS struct {
// The websocket connection.
ws *websocket.Conn
// Write Mutex
writeMutex *sync.Mutex
// Buffered channel of outbound messages.
send chan []byte
// String containing our random UUID
uuid string
}
func sendLatestJSON(){
var latestJSON []byte
statusTicker := time.NewTicker(time.Second)
for {
select {
case <-statusTicker.C:
clientMutex.Lock()
clients := len(clientMAP)
clientMutex.Unlock()
if clients > 0 {
latestJSON = AgentStatusJSON()
clientMutex.Lock()
for _, v := range clientMAP {
go v.write(websocket.TextMessage, latestJSON)
}
clientMutex.Unlock()
}
}
}
}
func AgentStatusWS(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
c := &WallboardWS{send: make(chan []byte, 256), ws: ws}
c.writeMutex = &sync.Mutex{}
uuid, _ := uuid.NewV4()
c.uuid = fmt.Sprintf("%s", uuid)
clientMutex.Lock()
clientMAP[c.uuid] = c
clientMutex.Unlock()
for {
_, _, err := c.ws.ReadMessage()
if err != nil {
break
}
}
c.CloseCleanup()
}
func (c *WallboardWS) write(mt int, payload []byte) error {
c.writeMutex.Lock()
defer c.writeMutex.Unlock()
c.ws.SetWriteDeadline(time.Now().Add(writeWait))
return c.ws.WriteMessage(mt, payload)
}
func (c *WallboardWS) CloseCleanup() {
// Close the WebSocket connection.
c.ws.Close()
// Remove the user from our user map.
clientMutex.Lock()
if _, ok := clientMAP[c.uuid]; ok {
delete(clientMAP, c.uuid)
}
clientMutex.Unlock()
}