-
Notifications
You must be signed in to change notification settings - Fork 8
/
websocket.go
111 lines (100 loc) · 2.1 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
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
package main
import (
"container/list"
"encoding/json"
"github.com/gorilla/websocket"
"log"
"net/http"
"runtime"
)
var chanList = list.New()
type conn struct {
stringc chan string
bytec chan []byte
}
func closeN(c *list.Element) {
wsMutex.Lock()
chanList.Remove(c)
wsMutex.Unlock()
}
func broadcastMessage(data string) {
wsMutex.Lock()
for e := chanList.Front(); e != nil; {
var c = e.Value.(conn)
go func() {
c.stringc <- data
}()
var next = e.Next()
e = next
}
wsMutex.Unlock()
}
func broadcastBMessage(data []byte) {
wsMutex.Lock()
for e := chanList.Front(); e != nil; {
var c = e.Value.(conn)
go func() {
c.bytec <- data
}()
var next = e.Next()
e = next
}
wsMutex.Unlock()
}
func handleMessages(c *websocket.Conn) {
var cChannel = make(chan string)
var bChannel = make(chan []byte)
wsMutex.Lock()
var li = chanList.PushBack(conn{
stringc: cChannel,
bytec: bChannel,
})
wsMutex.Unlock()
defer closeN(li)
// region Send DeviceInfo
log.Println("New connection from", c.RemoteAddr())
m, err := json.Marshal(currDevice)
if err != nil {
log.Println("Error serializing JSON: ", err)
}
err = c.WriteMessage(websocket.TextMessage, []byte(m))
if err != nil {
log.Println("Error sending message:", err, "dropping connection from", c.RemoteAddr())
return
}
// endregion
// region Client Loop
running := true
for running {
//_, _, err := c.ReadMessage()
//if err != nil {
// break
//}
select {
case msg := <-cChannel:
err = c.WriteMessage(websocket.TextMessage, []byte(msg))
if err != nil {
log.Println("Error sending message:", err, "dropping connection from", c.RemoteAddr())
running = false
break
}
case msg := <-bChannel:
err = c.WriteMessage(websocket.BinaryMessage, msg)
if err != nil {
log.Println("Error sending message:", err, "dropping connection from", c.RemoteAddr())
running = false
break
}
}
runtime.Gosched()
}
// endregion
}
func ws(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
handleMessages(c)
}