-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathwebsocket.go
119 lines (104 loc) · 2.18 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
112
113
114
115
116
117
118
119
package main
import (
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
)
type triggerAction struct {
Action string `json:"action"`
Row *preRow `json:"row"`
}
type wsClient struct {
conn *websocket.Conn
send chan triggerAction
}
const (
writeTimeout = 10 * time.Second
pongWait = 60 * time.Second
pingPeriod = 50 * time.Second
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
var backendUpdates chan triggerAction
func websocketUpgrader(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
defer ws.Close()
c := &wsClient{conn: ws, send: make(chan triggerAction)}
clients[c] = true
go c.writePump()
c.readPump()
}
var clients map[*wsClient]bool
func backendPump() {
backendUpdates = make(chan triggerAction)
clients = make(map[*wsClient]bool)
for {
select {
case rls := <-backendUpdates:
for c := range clients {
select {
case c.send <- rls:
default:
log.Println("CLOSE")
close(c.send)
delete(clients, c)
}
}
}
}
}
func (c *wsClient) writePump() {
ticker := time.NewTicker(pingPeriod)
defer ticker.Stop()
for {
select {
case rls := <-c.send:
err := c.conn.SetWriteDeadline(time.Now().Add(writeTimeout))
if err != nil {
log.Println("WRITE DEADLINE ERR", err)
}
err = c.conn.WriteJSON(rls)
if err != nil {
log.Println("WRITE ERR", err)
return
}
case <-ticker.C:
err := c.conn.SetWriteDeadline(time.Now().Add(writeTimeout))
if err != nil {
log.Println("PING DEADLINE ERR", err)
}
err = c.conn.WriteMessage(websocket.PingMessage, []byte{})
if err != nil {
log.Println("PING ERR", err)
return
}
}
}
}
func (c *wsClient) readPump() {
err := c.conn.SetReadDeadline(time.Now().Add(pongWait))
if err != nil {
log.Println("READ DEADLINE ERR", err)
return
}
c.conn.SetPongHandler(func(string) error {
err = c.conn.SetReadDeadline(time.Now().Add(pongWait))
if err != nil {
log.Println("READ DEADLINE ERR", err)
}
return nil
})
for {
_, _, err := c.conn.NextReader()
if err != nil {
log.Println("READ ERR", err)
break
}
}
}