-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
92 lines (73 loc) · 1.56 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
package main
import (
"log"
"time"
ws "github.com/gorilla/websocket"
"github.com/orcaman/concurrent-map"
)
var connPool cmap.ConcurrentMap
func init() {
connPool = cmap.New()
}
// Client represents a client
type Client struct {
conn *ws.Conn
connID string
writeChan chan []byte
}
// NewClient creates a new client object with the given websocket connection
func NewClient(c *ws.Conn) *Client {
client := &Client{
conn: c,
connID: c.RemoteAddr().String(),
writeChan: make(chan []byte),
}
go client.pingWorker()
go client.writeWorker()
go client.broadcastWorker()
log.Println("client", "new", client.connID)
connPool.Set(client.connID, client)
return client
}
// Close closes the underlying websocket connection
func (c *Client) Close(from string) {
connPool.Remove(c.connID)
c.conn.Close()
log.Println("client", "exit-from", from, c.connID)
}
func (c *Client) pingWorker() {
for {
if err := c.conn.WriteControl(
ws.PingMessage, nil, time.Now().Add(5*time.Second)); err != nil {
log.Println(err)
break
}
time.Sleep(5 * time.Second)
}
c.Close("ping")
}
func (c *Client) writeWorker() {
for {
data := <-c.writeChan
if err := c.conn.WriteMessage(ws.TextMessage, data); err != nil {
log.Println(err)
break
}
}
c.Close("write")
}
func (c *Client) broadcastWorker() {
for {
// read
_, data, err := c.conn.ReadMessage()
if err != nil {
log.Println(err)
break
}
// broadcast
for connTuple := range connPool.IterBuffered() {
connTuple.Val.(*Client).writeChan <- data
}
}
c.Close("broadcast")
}