-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
115 lines (96 loc) · 2.77 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
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
115
package main
import (
"net/http"
"strconv"
"sync"
"github.com/gorilla/websocket"
"github.com/jake-dog/opensimdash/hid"
)
var (
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
defaultWriter = &WebSockWriter{}
// ws is a wrapper around defaultWriter for faster JSON marshalling
ws = &webSockPackSender{
WebSockWriter: defaultWriter,
Buf: make([]byte, 0, 100), // Size large enough for marshalling!
}
)
func init() {
http.HandleFunc("/sock", wsEndpoint)
http.Handle("/", http.FileServer(http.Dir("static")))
}
type webSockPackSender struct {
*WebSockWriter
Buf []byte
}
// SendPack is about 6 times faster than json.Marshaler
func (ws *webSockPackSender) SendPack(d hid.TelemetryPack) {
ws.Buf = ws.Buf[:0]
ws.Buf = append(ws.Buf, `{"Gear":`...)
ws.Buf = strconv.AppendInt(ws.Buf, int64(d.GetGear()), 10) // Avoid allocs!
ws.Buf = append(ws.Buf, `,"Speed":`...)
ws.Buf = strconv.AppendInt(ws.Buf, int64(d.GetSpeed()), 10) // Avoid allocs!
ws.Buf = append(ws.Buf, `}`...)
ws.Write(ws.Buf)
}
// WebSockWriter provides a thread safe mechanism for performing synchronous
// writes to multiple websockets. Clients which disconnect are removed from the
// pool automatically.
type WebSockWriter struct {
writersmu sync.Mutex
writers []*websocket.Conn
}
// Write binary data to all connected websockets synchronously
func (w *WebSockWriter) Write(b []byte) (n int, err error) {
w.writersmu.Lock()
defer w.writersmu.Unlock()
// Send data to each WS client, and remove clients who throw errors
var i int
for _, ws := range w.writers {
if erro := ws.WriteMessage(1, b); erro != nil {
err = erro
// ws.Close() // shoudl we force close or let connection timeout?
} else {
w.writers[i] = ws
i++
}
}
w.writers = w.writers[:i]
if err != nil {
n = len(b)
}
return n, err
}
// Add a websocket to the pool of websockets being written to. Websockets that
// disconnect are automatically removed.
func (w *WebSockWriter) Add(ws *websocket.Conn) {
w.writersmu.Lock()
defer w.writersmu.Unlock()
// Add a WS, and create array if its not already there
if w.writers == nil {
w.writers = make([]*websocket.Conn, 0, 1)
}
w.writers = append(w.writers, ws)
}
// WriteMessage to all websockets
func WriteMessage(b []byte) (n int, err error) {
return defaultWriter.Write(b)
}
// AddWebSock to the pool of websockets
func AddWebSock(ws *websocket.Conn) {
defaultWriter.Add(ws)
}
func wsEndpoint(w http.ResponseWriter, r *http.Request) {
upgrader.CheckOrigin = func(r *http.Request) bool { return true }
// Upgrade connection to a WebSocket
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
logger.Println(err)
}
logger.Println("Client Connected")
// Add our new WS connection to the global WebSocketWriter
AddWebSock(ws)
}