-
Notifications
You must be signed in to change notification settings - Fork 0
/
08-pub-sub-and-pull-push-client-v2.cpp
59 lines (49 loc) · 1.9 KB
/
08-pub-sub-and-pull-push-client-v2.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
#include <zmq.hpp>
#include <iostream>
#include <sstream>
#include <unistd.h>
#include <cstdlib>
#include <ctime>
int main (int argc, char *argv[])
{
srand((unsigned int)time(NULL));
zmq::context_t context (1);
zmq::socket_t subscriber (context, zmq::socket_type::sub);
subscriber.connect("tcp://localhost:5557");
subscriber.setsockopt(ZMQ_SUBSCRIBE, "", 0);
zmq::socket_t publisher(context, ZMQ_PUSH);
publisher.connect("tcp://localhost:5558");
std::string clientID = argv[1];
while (1){
zmq_pollitem_t items[1];
items[0].socket = subscriber;
items[0].events = ZMQ_POLLIN;
zmq::poll(items, 1, 100);
if (items[0].revents & ZMQ_POLLIN){
zmq::message_t message;
subscriber.recv(message, zmq::recv_flags::none);
std::string smessage(static_cast<char*>(message.data()), message.size());
std::cout << clientID << ": receive status => " << smessage << std::endl;
}
else{
int rand = std::rand() % 101;
if (rand < 10){
sleep(1);
zmq::message_t message(clientID.length() + 6);
std::string msg = "(" + clientID + ":ON)";
memcpy (message.data (), msg.c_str(), msg.length()+1);
publisher.send(message, zmq::send_flags::none);
std::cout << clientID << ": send status - activated" << std::endl;
}
else if (rand > 90){
sleep(1);
zmq::message_t message(clientID.length() + 7);
std::string msg = "(" + clientID + ":OFF)";
memcpy (message.data (), msg.c_str(), msg.length()+1);
publisher.send(message, zmq::send_flags::none);
std::cout << clientID << ": send status - deactivated" << std::endl;
}
}
}
return 0;
}