-
Notifications
You must be signed in to change notification settings - Fork 0
/
websockethub.go
75 lines (65 loc) · 1.33 KB
/
websockethub.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
package gop5js
import (
"fmt"
"log"
"net/http"
"os"
"github.com/gorilla/websocket"
)
var wshub = newWebsocketHub()
type hub struct {
connections map[*websocket.Conn]*websocket.Conn
}
func newWebsocketHub() *hub {
return &hub{
connections: make(map[*websocket.Conn]*websocket.Conn),
}
}
func (h *hub) addConnection(c *websocket.Conn) {
h.connections[c] = c
}
func (h *hub) removeConnection(c *websocket.Conn) {
delete(h.connections, c)
}
func (h *hub) writeJSON(v interface{}) error {
for c := range h.connections {
err := c.WriteJSON(v)
if err != nil {
return err
}
}
return nil
}
func (h *hub) writeMessage(messageType int, data []byte) error {
for c := range h.connections {
err := c.WriteMessage(messageType, data)
if err != nil {
return err
}
}
return nil
}
func wsHandleFunc(w http.ResponseWriter, r *http.Request) {
upgrader := websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
defer conn.Close()
defer wshub.removeConnection(conn)
wshub.addConnection(conn)
for {
_, message, err := conn.ReadMessage()
if err != nil {
fmt.Println("error when reading from browser:", err)
fmt.Println("Program exit.")
os.Exit(1)
}
//fmt.Println(string(message))
nextFrame(message)
}
}