/
zmq2.h
111 lines (94 loc) · 3.08 KB
/
zmq2.h
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
102
103
104
105
106
107
108
109
110
111
/**
* Extending zmq::socket_t to send/receive multipart messages.
*
* More information here: http://thisthread.blogspot.com/2012/04/extending-zmqsockett.html
* Inspired by czmq, as described in the ZGuide: http://zguide.zeromq.org/page:all#A-High-Level-API-for-MQ
*/
#pragma once
#include <cstdint>
#include <vector>
#include <zmq.hpp>
namespace zmq
{
typedef std::vector<std::string> Frames;
class Socket : public socket_t
{
public:
Socket(context_t& context, int type) : socket_t(context, type) {}
Socket(context_t& context, int type, const std::string& id) : socket_t(context, type)
{
zmq_setsockopt(this->operator void*(), ZMQ_IDENTITY, id.c_str(), id.length());
}
bool send(const std::string& frame, int flags =0)
{
zmq::message_t msg(frame.length());
memcpy(msg.data(), frame.c_str(), frame.length());
return socket_t::send(msg, flags);
}
bool send(const Frames& frames)
{
if(!frames.size())
throw error_t();
// all frames but last one
for(unsigned int i = 0; i < frames.size() - 1; ++i)
{
if(!send(frames[i], ZMQ_SNDMORE))
return false;
if(!sendSeparator())
return false;
}
// last frame
return send(frames.back());
}
/*
n: expected number of frames
*/
Frames blockingRecv(int n, bool checked =true)
{
Frames frames;
frames.reserve(n);
int currentFrame = 1;
do {
zmq::message_t message;
if(!socket_t::recv(&message, 0))
throw error_t();
if(!(currentFrame++ % 2))
{ // skipping separators
if(message.size())
throw error_t();
}
else
{
const char* base = static_cast<const char*>(message.data());
frames.push_back(std::string(base, base + message.size()));
}
} while(sockopt_rcvmore());
if(checked && frames.size() != n)
throw error_t();
return frames;
}
std::string recvAsString(int flags =0)
{
zmq::message_t message;
if(!socket_t::recv(&message, flags))
throw error_t();
const char* base = static_cast<const char*>(message.data());
return std::string(base, base + message.size());
}
private:
Socket(const Socket&);
void operator=(const Socket&);
bool sendSeparator()
{
zmq::message_t msg;
return socket_t::send(msg, ZMQ_SNDMORE);
}
bool sockopt_rcvmore()
{
int64_t rcvmore;
size_t type_size = sizeof(int64_t);
getsockopt(ZMQ_RCVMORE, &rcvmore, &type_size);
return rcvmore ? true : false;
}
};
}