forked from johnlauer/serial-port-json-server
-
Notifications
You must be signed in to change notification settings - Fork 101
/
conn.go
59 lines (49 loc) · 1.09 KB
/
conn.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
// Supports Windows, Linux, Mac, and Raspberry Pi
// Going to add SSL
package main
import (
"log"
"net/http"
"github.com/gorilla/websocket"
)
type connection struct {
// The websocket connection.
ws *websocket.Conn
// Buffered channel of outbound messages.
send chan []byte
}
func (c *connection) reader() {
for {
_, message, err := c.ws.ReadMessage()
if err != nil {
break
}
h.broadcast <- message
}
c.ws.Close()
}
func (c *connection) writer() {
for message := range c.send {
err := c.ws.WriteMessage(websocket.TextMessage, message)
if err != nil {
break
}
}
c.ws.Close()
}
func wsHandler(w http.ResponseWriter, r *http.Request) {
log.Print("Started a new websocket handler")
ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
if _, ok := err.(websocket.HandshakeError); ok {
http.Error(w, "Not a websocket handshake", 400)
return
} else if err != nil {
return
}
//c := &connection{send: make(chan []byte, 256), ws: ws}
c := &connection{send: make(chan []byte, 256*10), ws: ws}
h.register <- c
defer func() { h.unregister <- c }()
go c.writer()
c.reader()
}