pub_sub.cpp
1.61 KB
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
/**
* Redox example for basic pubsub usage.
*/
#include <stdlib.h>
#include <iostream>
#include "redox.hpp"
using namespace std;
int main(int argc, char *argv[]) {
redox::Redox publisher; // Initialize Redox (default host/port)
if (!publisher.connect()) return 1; // Start the event loop
redox::Subscriber subscriber;
if(!subscriber.connect()) return 1;
auto got_message = [](const string& topic, const string& msg) {
cout << topic << ": " << msg << endl;
};
auto subscribed = [](const string& topic) {
cout << "> Subscribed to " << topic << endl;
};
auto unsubscribed = [](const string& topic) {
cout << "> Unsubscribed from " << topic << endl;
};
subscriber.psubscribe("news", got_message, subscribed, unsubscribed);
subscriber.subscribe("sports", got_message, subscribed, unsubscribed);
subscriber.subscribe("other", got_message, subscribed, unsubscribed);
this_thread::sleep_for(chrono::milliseconds(10));
publisher.publish("news", "one");
publisher.publish("news", "two");
publisher.publish("sports", "three");
this_thread::sleep_for(chrono::milliseconds(10));
subscriber.unsubscribe("sports");
this_thread::sleep_for(chrono::milliseconds(10));
publisher.publish("sports", "\"UH OH\"");
publisher.publish("news", "four");
this_thread::sleep_for(chrono::milliseconds(10));
subscriber.punsubscribe("news");
this_thread::sleep_for(chrono::milliseconds(10));
publisher.publish("sports", "\"UH OH\"");
publisher.publish("news", "\"UH OH\"");
this_thread::sleep_for(chrono::milliseconds(10));
subscriber.disconnect();
publisher.disconnect();
return 0;
}