-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
73 lines (60 loc) · 1.4 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
package main
import (
"encoding/json"
"log"
"github.com/gorilla/websocket"
)
type ClientList map[*Client]bool
type Client struct {
connection *websocket.Conn
manager *Manager
// egress is used to to avoid concurrent writes on the websocket connection
egress chan Event
}
func NewClient(conn *websocket.Conn, manager *Manager) *Client {
return &Client{
connection: conn,
manager: manager,
egress: make(chan Event),
}
}
func (c *Client) readMessages() {
defer func() {
// cleanup connection
c.manager.removeClient(c)
}()
for {
_, payload, err := c.connection.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("error reading message: %v", err)
}
break
}
var request Event
if err := json.Unmarshal(payload, &request); err != nil {
log.Printf("error unmarshalling request: %v", err)
break
}
}
}
func (c *Client) writeMessages() {
defer func() {
c.manager.removeClient(c)
}()
for {
select {
case message, ok := <-c.egress:
if !ok {
if err := c.connection.WriteMessage(websocket.CloseMessage, nil); err != nil {
log.Println("connection closed: ", err)
}
return
}
if err := c.connection.WriteMessage(websocket.TextMessage, message); err != nil {
log.Printf("failed to send message: %v", err)
}
log.Println("message sent")
}
}
}