pub_sub.cpp
1.59 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include "hiredis/hiredis.h"
#include "hiredis/async.h"
#include "hiredis/adapters/libev.h"
#include <iostream>
#include "../src/redox.hpp"
using namespace std;
int main(int argc, char *argv[]) {
redox::Redox rdx; // Initialize Redox (default host/port)
if (!rdx.start()) return 1; // Start the event loop
redox::Redox rdx_pub;
if(!rdx_pub.start()) 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;
};
rdx.psubscribe("news", got_message, subscribed, unsubscribed);
rdx.subscribe("sports", got_message, subscribed, unsubscribed);
this_thread::sleep_for(chrono::milliseconds(20));
for(auto s : rdx.subscribed_topics()) cout << "topic: " << s << endl;
rdx_pub.publish("news", "hello!");
rdx_pub.publish("news", "whatup");
rdx_pub.publish("sports", "yo");
this_thread::sleep_for(chrono::seconds(1));
rdx.unsubscribe("sports");
rdx_pub.publish("sports", "yo");
rdx_pub.publish("news", "whatup");
this_thread::sleep_for(chrono::milliseconds(1));
rdx.punsubscribe("news");
rdx_pub.publish("sports", "yo");
rdx_pub.publish("news", "whatup", [](const string& topic, const string& msg) {
cout << "published to " << topic << ": " << msg << endl;
});
rdx_pub.publish("news", "whatup");
rdx.block();
rdx_pub.block();
}