-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
100 lines (87 loc) · 2.16 KB
/
client.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
package main
import (
"encoding/json"
"log"
"time"
"github.com/gorilla/websocket"
)
var (
pongWait = 10 * time.Second
pingInterval = (pongWait * 9) / 10
)
type ClientList map[*Client]bool
type Client struct {
connection *websocket.Conn
manager *Manager
egress chan Event // This is used to avoid concurrent writes on the websocket
}
func NewClient(conn *websocket.Conn, manager *Manager) *Client {
return &Client{
connection: conn,
manager: manager,
egress: make(chan Event),
}
}
func (c *Client) readMessages() {
defer func() {
c.manager.removeClient(c)
}()
if err := c.connection.SetReadDeadline(time.Now().Add(pongWait)); err != nil {
log.Println(err)
return
}
c.connection.SetReadLimit(512)
c.connection.SetPongHandler(c.pongHandler)
for {
_, payload, err := c.connection.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Println("Unexpected Close error")
}
break
}
var request Event
if err := json.Unmarshal(payload, &request); err != nil {
log.Printf("error marshalling event: %v", err)
break
}
if err := c.manager.routeEvent(request, c); err != nil {
log.Println("error handling message: ", err)
}
}
}
func (c *Client) writeMessages() {
defer func() {
c.manager.removeClient(c)
}()
ticker := time.NewTicker(pingInterval)
for {
select {
case message, ok := <-c.egress:
if !ok {
if err := c.connection.WriteMessage(websocket.CloseMessage, nil); err != nil {
log.Println("connection closed")
}
return
}
data, err := json.Marshal(message)
if err != nil {
log.Println(err)
}
if err := c.connection.WriteMessage(websocket.TextMessage, data); err != nil {
log.Printf("failed to send message: %v", err)
}
log.Println("message sent")
case <-ticker.C:
log.Println("Ping")
if err := c.connection.WriteMessage(websocket.PingMessage, []byte(``)); err != nil {
log.Println("writeMessage Error:", err)
return
}
}
}
}
func (c *Client) pongHandler(pongMsg string) error {
log.Println("pong")
return c.connection.SetReadDeadline(time.Now().Add(pongWait))
}