-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
72 lines (59 loc) · 1.52 KB
/
server.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
package websocket
import (
"net/http"
"sync"
runtimeYanic "github.com/FreifunkBremen/yanic/runtime"
httpLib "github.com/genofire/golang-lib/http"
"github.com/genofire/golang-lib/log"
"golang.org/x/net/websocket"
"github.com/FreifunkBremen/freifunkmanager/runtime"
)
var nodes *runtime.Nodes
var clients map[string]*Client
var clientsMutex sync.Mutex
var stats *runtimeYanic.GlobalStats
var commands *runtime.Commands
func Start(nodeBind *runtime.Nodes, commandsBind *runtime.Commands) {
nodes = nodeBind
commands = commandsBind
clients = make(map[string]*Client)
http.Handle("/websocket", websocket.Handler(func(ws *websocket.Conn) {
r := ws.Request()
ip := httpLib.GetRemoteIP(r)
defer func() {
ws.Close()
clientsMutex.Lock()
delete(clients, ip)
clientsMutex.Unlock()
log.HTTP(r).Info("client disconnected")
}()
log.HTTP(r).Infof("new client")
client := NewClient(ip, ws)
clientsMutex.Lock()
clients[ip] = client
clientsMutex.Unlock()
client.Listen()
}))
nodes.AddNotify(NotifyNode)
}
func NotifyNode(node *runtime.Node, system bool) {
msgType := MessageTypeCurrentNode
if system {
msgType = MessageTypeSystemNode
}
SendAll(Message{Type: msgType, Node: node})
}
func NotifyStats(data *runtimeYanic.GlobalStats) {
stats = data
SendAll(Message{Type: MessageTypeStats, Body: data})
}
func SendAll(msg Message) {
clientsMutex.Lock()
for _, c := range clients {
c.Write(&msg)
}
clientsMutex.Unlock()
}
func Close() {
log.Log.Infof("websocket stopped with %d clients", len(clients))
}