-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
68 lines (57 loc) · 1.64 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
package deje
import (
"github.com/DJDNS/go-deje/document"
"github.com/jcelliott/turnpike"
)
// Contains a document and a WAMP connection.
type Client struct {
Doc *document.Document
Topic string
onEvent *OnEventCallback
tpClient *turnpike.Client
}
func NewClient(topic string) Client {
doc := document.NewDocument()
return Client{
Doc: &doc,
Topic: topic,
tpClient: turnpike.NewClient(),
}
}
// When a session connects, this callback is provided with the session
// ID value. sessionId is just a server-chosen string.
type OnConnectCallback func(sessionId string)
// Called when another peer in the same WAMP topic publishes a
// JSON-compatible event to all subscribers.
type OnEventCallback func(event interface{})
// Set callback to be executed when a successful connection has been
// made to a WAMP router.
func (c *Client) SetConnectCallback(callback OnConnectCallback) {
c.tpClient.SetSessionOpenCallback(callback)
}
// Set callback to be executed when a published event is received.
func (c *Client) SetEventCallback(callback OnEventCallback) {
c.onEvent = &callback
}
// Publish an event to all subscribers. Can be any JSON-compatible
// value.
func (c *Client) Publish(event interface{}) error {
return c.tpClient.PublishExcludeMe(
c.Topic,
event,
)
}
// Connect to a WAMP router. This also calls the 'connect' callback on
// success.
func (c *Client) Connect(url string) error {
err := c.tpClient.Connect(url, "http://localhost/")
if err != nil {
return err
}
handler := func(topic string, event interface{}) {
if c.onEvent != nil {
(*c.onEvent)(event)
}
}
return c.tpClient.Subscribe(c.Topic, handler)
}