-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
114 lines (96 loc) · 2.4 KB
/
main.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
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
105
106
107
108
109
110
111
112
113
114
package main
import (
"fmt"
"github.com/gorilla/websocket"
"log"
"net/http"
"sync"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func main() {
http.HandleFunc("/lightbulb", lightBulbHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
var clients = make(map[*websocket.Conn]bool)
var clientsMutex sync.Mutex
var lightBulb = false
var lightBulbMutex sync.Mutex
func lightBulbHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Connection Opened: ", r.RemoteAddr)
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("upgrade err:", err)
return
}
defer func() {
DeleteClientFromConnectionsWithLock(c)
err := c.Close()
if err != nil {
return
}
}()
AddClientToConnectionsWithLock(c)
resMessage := GetLightBulbStateAsByteArrayWithLock()
if err := c.WriteMessage(websocket.TextMessage, resMessage); err != nil {
fmt.Println("Error writing message:", err)
}
for {
_, _, err := c.ReadMessage()
log.Println("Light bulb switched: ", r.RemoteAddr)
if err != nil {
log.Println("read:", err)
break
}
resMessage := SwitchLightBulbAndGetStateWithLock()
BroadcastNewLightBulbStateToAllClients(resMessage)
}
}
func BroadcastNewLightBulbStateToAllClients(resMessage []byte) {
clientsMutex.Lock()
for client := range clients {
go BroadcastNewLightBulbStateToClient(resMessage, client)
}
clientsMutex.Unlock()
}
func BroadcastNewLightBulbStateToClient(resMessage []byte, client *websocket.Conn) {
if err := client.WriteMessage(websocket.TextMessage, resMessage); err != nil {
fmt.Println("Error writing message:", err)
}
}
func DeleteClientFromConnectionsWithLock(c *websocket.Conn) {
clientsMutex.Lock()
delete(clients, c)
clientsMutex.Unlock()
}
func AddClientToConnectionsWithLock(c *websocket.Conn) {
clientsMutex.Lock()
clients[c] = true
clientsMutex.Unlock()
}
func GetLightbulbStateAsByteArray() []byte {
var resMessage []byte
if lightBulb {
resMessage = []byte("true")
} else {
resMessage = []byte("false")
}
return resMessage
}
func GetLightBulbStateAsByteArrayWithLock() []byte {
defer lightBulbMutex.Unlock()
lightBulbMutex.Lock()
return GetLightbulbStateAsByteArray()
}
func SwitchLightBulb() {
lightBulb = !lightBulb
}
func SwitchLightBulbAndGetStateWithLock() []byte {
defer lightBulbMutex.Unlock()
lightBulbMutex.Lock()
SwitchLightBulb()
return GetLightbulbStateAsByteArray()
}