diff -r 000000000000 -r e5d547ab0c51 src/ZeroMQ.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/ZeroMQ.h Sun May 01 18:23:45 2022 +0200 @@ -0,0 +1,70 @@ +/** + * Relational pipes + * Copyright © 2022 František Kučera (Frantovo.cz, GlobalCode.info) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#pragma once + +#include +#include +#include +#include + +namespace relpipe { +namespace in { +namespace zeromq { + +class ZeroMQ { +private: + const static size_t MSG_SIZE = 8192; // TODO: configurable/dynamic + std::string queueName; + mqd_t handle = -2; + bool unlinkOnClose = false; + + ZeroMQ(std::string queueName, mqd_t handle, bool unlinkOnClose) : queueName(queueName), handle(handle), unlinkOnClose(unlinkOnClose) { + } + +public: + + virtual ~ZeroMQ() { + if (handle >= 0) mq_close(handle); + if (unlinkOnClose) mq_unlink(queueName.c_str()); + } + + static ZeroMQ* open(std::string queueName, bool unlinkOnClose = false) { + mqd_t handle = mq_open(queueName.c_str(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); + if (handle >= 0) return new ZeroMQ(queueName, handle, unlinkOnClose); + else throw std::logic_error("Unable to open ZeroMQ: " + queueName + " error: " + strerror(errno)); + } + + void send(std::string message) { + int result = mq_send(handle, message.c_str(), message.size(), 0); + if (result) throw std::logic_error("Unable to send message to" + queueName + " error: " + strerror(errno)); + } + + std::string receive() { + char buffer[MSG_SIZE + 1]; + memset(buffer, 0, MSG_SIZE + 1); + ssize_t msgSize = mq_receive(handle, buffer, MSG_SIZE, nullptr); + + if (msgSize > sizeof (buffer))throw std::logic_error("Invalid ZeroMQ message size."); + else if (msgSize >= 0) return std::string(buffer, msgSize); + else throw std::logic_error("Unable to receive ZeroMQ message from " + queueName + " error: " + strerror(errno)); + } + +}; + +} +} +}