]> code.octet-stream.net Git - broadcaster/blob - server/command.go
Simplify package names
[broadcaster] / server / command.go
1 package main
2
3 import (
4 "code.octet-stream.net/broadcaster/internal/protocol"
5 "encoding/json"
6 "golang.org/x/net/websocket"
7 "sync"
8 )
9
10 type CommandRouter struct {
11 connsMutex sync.Mutex
12 conns map[int]*websocket.Conn
13 }
14
15 var commandRouter CommandRouter
16
17 func InitCommandRouter() {
18 commandRouter.conns = make(map[int]*websocket.Conn)
19 }
20
21 func (c *CommandRouter) AddWebsocket(radioId int, ws *websocket.Conn) {
22 c.connsMutex.Lock()
23 defer c.connsMutex.Unlock()
24 c.conns[radioId] = ws
25 }
26
27 func (c *CommandRouter) RemoveWebsocket(ws *websocket.Conn) {
28 c.connsMutex.Lock()
29 defer c.connsMutex.Unlock()
30 key := -1
31 for k, v := range c.conns {
32 if v == ws {
33 key = k
34 }
35 }
36 if key != -1 {
37 delete(c.conns, key)
38 }
39
40 }
41
42 func (c *CommandRouter) Stop(radioId int) {
43 c.connsMutex.Lock()
44 defer c.connsMutex.Unlock()
45 ws := c.conns[radioId]
46 if ws != nil {
47 stop := protocol.StopMessage{
48 T: protocol.StopType,
49 }
50 msg, _ := json.Marshal(stop)
51 ws.Write(msg)
52 }
53 }