-
Notifications
You must be signed in to change notification settings - Fork 17
/
client.go
72 lines (64 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
package kaca
import (
"github.com/gorilla/websocket"
"log"
"math/rand"
"net/url"
)
type client struct {
id uint64
addr string
path string
conn *websocket.Conn
}
func NewClient(addr, path string) *client {
u := url.URL{Scheme: "ws", Host: addr, Path: path}
log.Printf("connecting to %s", u.String())
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatal("dial:", err)
}
return &client{
id: uint64(rand.Int63()),
addr: addr,
path: path,
conn: c,
}
}
func (c *client) Broadcast(message string) {
err := c.conn.WriteMessage(websocket.TextMessage, []byte(message))
if err != nil {
log.Println("write:", err)
}
}
func (c *client) Pub(topic, message string) {
sendMsg := PUB_PREFIX + topic + SPLIT_LINE + message
err := c.conn.WriteMessage(websocket.TextMessage, []byte(sendMsg))
if err != nil {
log.Println("write:", err)
}
}
func (c *client) Sub(topic string) {
sendMsg := SUB_PREFIX + topic
err := c.conn.WriteMessage(websocket.TextMessage, []byte(sendMsg))
if err != nil {
log.Println("write:", err)
}
log.Println("sub topic :" + topic + "success")
}
func (c *client) ConsumeMessage(f func(m string)) {
go func() {
for {
_, message, err := c.conn.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
log.Printf("recv: %s", message)
f(string(message))
}
}()
}
func (c *client) Shutdown() {
c.conn.Close()
}