-
Notifications
You must be signed in to change notification settings - Fork 1
/
pubsub.cpp
101 lines (81 loc) · 2.17 KB
/
pubsub.cpp
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
100
101
/*Example code for pub/sub
run as publisher
./pubsub pub <channelName> <message>
run as subscriber
./pubsub sub <channelName>*/
/*----------------------
Publish and Subscribe
------------------------*/
#include <signal.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <hiredis/hiredis.h>
#include <hiredis/async.h>
#include <hiredis/adapters/libevent.h>
using namespace std;
void subCallback(redisAsyncContext *c, void *r, void *privdata) {
redisReply *reply = (redisReply*)r;
if (reply == NULL){
cout<<"Response not recev"<<endl;
return;
}
if(reply->type == REDIS_REPLY_ARRAY & reply->elements == 3)
{
if(strcmp( reply->element[0]->str,"subscribe") != 0)
{
cout<<"Message received -> "<<
reply->element[2]->str<<"( on channel : "<<reply->element[1]->str<<")"<<endl;
}
}
}
void pubCallback(redisAsyncContext *c, void *r, void *privdata) {
redisReply *reply = (redisReply*)r;
if (reply == NULL){
cout<<"Response not recev"<<endl;
return;
}
cout<<"message published"<<endl;
redisAsyncDisconnect(c);
}
int main(int argv, char** args)
{
string processName(args[1]);
signal(SIGPIPE, SIG_IGN);
struct event_base*
base = event_base_new();
redisAsyncContext*
_redisContext = redisAsyncConnect("127.0.0.1", 6379);
if (_redisContext->err) {
/* Let context leak for now... */
cout<<"Error: "<< _redisContext->errstr<<endl;
return 1;
}
redisLibeventAttach(_redisContext,base);
int status;
//Act as publisher
if(processName.compare("pub") == 0)
{
string command ("publish ");
command.append(args[2]);
command.append (" ");
command.append(args[3]);
status = redisAsyncCommand(_redisContext,
pubCallback,
(char*)"pub", command.c_str());
}
//Act as subscriber
else if(processName.compare("sub") == 0)
{
string command ("subscribe ");
command.append(args[2]);
status = redisAsyncCommand(_redisContext,
subCallback,
(char*)"sub", command.c_str());
}
else
cout<<"Try pub or sub"<<endl;
event_base_dispatch(base);
return 0;
}