Branch data Line data Source code
1 : : #include "ZeroMQSocket.hpp"
2 : :
3 : : #include <iostream>
4 : :
5 : : namespace MQ {
6 : 3 : void ZeroMQSocket::close() {
7 : 3 : std::cout << "Closing socket\n";
8 : 3 : m_socket.close();
9 : 3 : }
10 : :
11 : 3 : auto ZeroMQSocket::bind(const std::string& endpoint) -> bool {
12 : 3 : std::cout << "Binding to " << endpoint << "\n";
13 : : try {
14 : 3 : m_socket.set(zmq::sockopt::linger, 0);
15 : 3 : m_socket.bind(endpoint);
16 : 2 : return true;
17 : 1 : } catch (const zmq::error_t& e) {
18 : 1 : std::cout << "Error binding to " << endpoint << ": " << e.what() << "\n";
19 : 1 : return false;
20 : 1 : }
21 : : }
22 : :
23 : 0 : auto ZeroMQSocket::subscribe(const std::string& topic) -> bool {
24 : 0 : std::cout << "Subscribing to \"" << topic << "\"\n";
25 : : try {
26 : 0 : m_socket.set(zmq::sockopt::subscribe, topic);
27 : 0 : return true;
28 : 0 : } catch (const zmq::error_t& e) {
29 : 0 : std::cout << "Error subscribing to " << topic << ": " << e.what() << "\n";
30 : 0 : return false;
31 : 0 : }
32 : : }
33 : :
34 : 2 : auto ZeroMQSocket::connect(const std::string& endpoint) -> bool {
35 : 2 : std::cout << "Connecting to " << endpoint << "\n";
36 : : try {
37 : 2 : m_socket.set(zmq::sockopt::linger, 0);
38 : 2 : m_socket.connect(endpoint);
39 : 1 : return true;
40 : 1 : } catch (const zmq::error_t& e) {
41 : 1 : std::cout << "Error connecting to " << endpoint << ": " << e.what() << "\n";
42 : 1 : return false;
43 : 1 : }
44 : : }
45 : :
46 : 1 : auto ZeroMQSocket::send(const std::vector<uint8_t>& data) -> bool {
47 : 1 : zmq::message_t msg(data.size());
48 : 1 : memcpy(msg.data(), data.data(), data.size());
49 : 1 : auto res = m_socket.send(msg, zmq::send_flags::none);
50 : 2 : return res.has_value();
51 : 1 : }
52 : :
53 : 1 : auto ZeroMQSocket::receive() -> std::optional<std::vector<uint8_t>> {
54 : 1 : zmq::message_t msg;
55 : 1 : if (!m_socket.recv(msg, zmq::recv_flags::none)) {
56 : 0 : return {};
57 : : }
58 : 1 : std::vector<uint8_t> data(msg.size());
59 : 1 : memcpy(data.data(), msg.data(), msg.size());
60 : 1 : return data;
61 : 1 : }
62 : :
63 : : } // namespace MQ
|