-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzmq4_test.go
99 lines (87 loc) · 1.77 KB
/
zmq4_test.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
93
94
95
96
97
98
99
package zmq_comparison
import (
"context"
"log"
"strings"
"testing"
"time"
"github.com/go-zeromq/zmq4"
)
func TestZMQ4(t *testing.T) {
abort := make(chan bool)
go zmq4_sub(abort)
zmq4_pub(2*time.Second, abort)
}
func zmq4_pub(lifetime time.Duration, abort chan bool) {
log.SetPrefix("psenvpub: ")
// prepare the publisher
pub := zmq4.NewPub(context.Background())
defer pub.Close()
err := pub.Listen("tcp://*:5563")
if err != nil {
log.Fatalf("could not listen: %v", err)
}
msgA := zmq4.NewMsgFrom(
[]byte("A"),
[]byte("We don't want to see this"),
)
msgB := zmq4.NewMsgFrom(
[]byte("B"),
[]byte("We would like to see this"),
)
done := time.NewTimer(lifetime)
ticker := time.NewTicker(100 * time.Millisecond)
for {
select {
case <-done.C:
abort <- true
return
case <-ticker.C:
// Write two messages, each with an envelope and content
err = pub.Send(msgA)
if err != nil {
log.Fatal(err)
}
err = pub.Send(msgB)
if err != nil {
log.Fatal(err)
}
}
}
}
func zmq4_sub(abort chan bool) {
log.SetPrefix("psenvsub: ")
// Prepare our subscriber
sub := zmq4.NewSub(context.Background())
defer sub.Close()
err := sub.Dial("tcp://localhost:5563")
if err != nil {
log.Fatalf("could not dial: %v", err)
}
err = sub.SetOption(zmq4.OptionSubscribe, "B")
if err != nil {
log.Fatalf("could not subscribe: %v", err)
}
mchan := make(chan zmq4.Msg)
go func() {
for {
// Read envelope
msg, err := sub.Recv()
if err != nil {
if strings.Contains(err.Error(), "context cancel") {
return
}
log.Fatalf("could not receive message: %v", err)
}
mchan <- msg
}
}()
for {
select {
case <-abort:
return
case msg := <-mchan:
log.Printf("[%s] %s\n", msg.Frames[0], msg.Frames[1])
}
}
}