-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhub.go
More file actions
64 lines (57 loc) · 1.28 KB
/
Copy pathhub.go
File metadata and controls
64 lines (57 loc) · 1.28 KB
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
package websocketserver
import(
"github.com/gorilla/websocket"
"fmt"
)
type hub struct {
connections map[string]*connection
inbox chan *message
register chan *connection
unregister chan *connection
receiveHandler func(string, string) string
}
type connection struct {
id string
ws *websocket.Conn
outbox chan []byte
}
type message struct {
connid string
data []byte
}
func (h *hub) run() {
for {
select {
case c := <-h.register:
fmt.Println("registered")
h.connections[c.id] = c
case c := <-h.unregister:
fmt.Println("unregistered")
if _, ok := h.connections[c.id]; ok {
delete(h.connections, c.id)
close(c.outbox)
}
case m := <-h.inbox:
h.connections[m.connid].outbox <- []byte(h.receiveHandler(m.connid, string(m.data)))
}
}
}
func (c *connection) reader() {
for {
_, data, err := c.ws.ReadMessage()
if err != nil {
break
}
h.inbox <- &message{c.id, data}
}
c.ws.Close()
}
func (c *connection) writer() {
for data := range c.outbox {
err := c.ws.WriteMessage(websocket.TextMessage, data)
if err != nil {
break
}
}
c.ws.Close()
}