This repository has been archived by the owner on May 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
client.go
85 lines (68 loc) · 2.1 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
package main
import (
"flag"
"log"
"sync"
"time"
wwr "github.com/qbeon/webwire-go"
wwrclt "github.com/qbeon/webwire-go/client"
)
var serverAddr = flag.String("addr", ":8081", "server address")
var counterTarget = flag.Uint("n", 6, "number of signals to listen for")
// PubSubClient implements the wwrclt.Implementation interface
type PubSubClient struct {
connection *wwrclt.Client
target uint
counter uint
targetReached sync.WaitGroup
}
// NewPubSubClient constructs and returns a new pub-sub client instance
func NewPubSubClient(serverAddr string, counterTarget uint) *PubSubClient {
newPubSubClient := &PubSubClient{
target: counterTarget,
counter: 0,
targetReached: sync.WaitGroup{},
}
newPubSubClient.targetReached.Add(int(counterTarget))
// Initialize connection
newPubSubClient.connection = wwrclt.NewClient(
serverAddr,
newPubSubClient,
wwrclt.Options{
// Default timeout for timed requests
DefaultRequestTimeout: 10 * time.Second,
ReconnectionInterval: 2 * time.Second,
},
)
return newPubSubClient
}
// OnDisconnected implements the wwrclt.Implementation interface
func (clt *PubSubClient) OnDisconnected() {}
// OnSessionClosed implements the wwrclt.Implementation interface
func (clt *PubSubClient) OnSessionClosed() {}
// OnSessionCreated implements the wwrclt.Implementation interface
func (clt *PubSubClient) OnSessionCreated(_ *wwr.Session) {}
// OnSignal implements the wwrclt.Implementation interface
func (clt *PubSubClient) OnSignal(message wwr.Payload) {
clt.counter++
log.Printf(
"Signal %d of %d received: %s",
clt.counter,
clt.target,
string(message.Data),
)
clt.targetReached.Done()
}
// AwaitCounterTargetReached blocks the calling goroutine until the counter
// target is reached
func (clt *PubSubClient) AwaitCounterTargetReached() {
clt.targetReached.Wait()
}
func main() {
// Parse command line arguments
flag.Parse()
// Initialize a new pub-sub client instance
client := NewPubSubClient(*serverAddr, *counterTarget)
// Wait until N signals are received before disconnecting
client.AwaitCounterTargetReached()
}