forked from pebbe/zmq4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clonecli4.go
84 lines (75 loc) · 1.93 KB
/
clonecli4.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
//
// Clone client Model Four
//
package main
import (
zmq "github.com/pebbe/zmq4"
"github.com/pebbe/zmq4/examples/kvsimple"
"fmt"
"math/rand"
"time"
)
const (
SUBTREE = "/client/"
)
func main() {
snapshot, _ := zmq.NewSocket(zmq.DEALER)
snapshot.Connect("tcp://localhost:5556")
subscriber, _ := zmq.NewSocket(zmq.SUB)
subscriber.SetSubscribe(SUBTREE)
subscriber.Connect("tcp://localhost:5557")
publisher, _ := zmq.NewSocket(zmq.PUSH)
publisher.Connect("tcp://localhost:5558")
kvmap := make(map[string]*kvsimple.Kvmsg)
rand.Seed(time.Now().UnixNano())
// We first request a state snapshot:
sequence := int64(0)
snapshot.SendMessage("ICANHAZ?", SUBTREE)
for {
kvmsg, err := kvsimple.RecvKvmsg(snapshot)
if err != nil {
break // Interrupted
}
if key, _ := kvmsg.GetKey(); key == "KTHXBAI" {
sequence, _ := kvmsg.GetSequence()
fmt.Println("I: received snapshot =", sequence)
break // Done
}
kvmsg.Store(kvmap)
}
snapshot.Close()
poller := zmq.NewPoller()
poller.Add(subscriber, zmq.POLLIN)
alarm := time.Now().Add(1000 * time.Millisecond)
for {
tickless := alarm.Sub(time.Now())
if tickless < 0 {
tickless = 0
}
polled, err := poller.Poll(tickless)
if err != nil {
break // Context has been shut down
}
if len(polled) == 1 {
kvmsg, err := kvsimple.RecvKvmsg(subscriber)
if err != nil {
break // Interrupted
}
// Discard out-of-sequence kvmsgs, incl. heartbeats
if seq, _ := kvmsg.GetSequence(); seq > sequence {
sequence = seq
kvmsg.Store(kvmap)
fmt.Println("I: received update =", sequence)
}
}
// If we timed-out, generate a random kvmsg
if time.Now().After(alarm) {
kvmsg := kvsimple.NewKvmsg(0)
kvmsg.SetKey(fmt.Sprintf("%s%d", SUBTREE, rand.Intn(10000)))
kvmsg.SetBody(fmt.Sprint(rand.Intn(1000000)))
kvmsg.Send(publisher)
alarm = time.Now().Add(1000 * time.Millisecond)
}
}
fmt.Printf("Interrupted\n%d messages in\n", sequence)
}