I want to have an exclusive pair of 2 sockets to allow bilateral communication between 2 separate applications. I use ZeroMQ cppzmq
.
In the client, I am checking if the server is live by a handshake.It could be the case that the server is not online yet, when I start the client.This causes the client to hang at the moment, and i need to force quit the application.
I am trying to implement a timeout on the client side, to exit the application after no handshake OK message is received. I thought I could do this with ZMQ_CONNECT_TIMEOUT
, ZMQ_SNDTIMEO
or ZMQ_RCVTIMEO
. Unfortunately, this does not work as I intended, the client keeps hanging at the end of the program.
How can I stop all blocking actions at the return of the program? Please note that this is an MVCE, and I am running this in a bigger application. So simply checking if (incoming_msg != "OK") exit(0);
works here, but is not a usefull solution.
Server:
// server.cpp#include <iostream>#include <zmq.hpp>int main(){ zmq::context_t context(1); zmq::socket_t socket(context, zmq::socket_type::pair); socket.bind("tcp://*:5555"); while (true) { zmq::message_t incoming; auto ret = socket.recv(incoming, zmq::recv_flags::none); std::string incoming_str = incoming.to_string(); std::cout << "Received request: " << incoming_str << std::endl; if (incoming_str == "connected") { std::cout << " Sending OK" << std::endl; zmq::message_t ack(2); memcpy(ack.data(), "OK", 2); socket.send(ack, zmq::send_flags::none); } } return 0;}
Client:
// client.cpp#include <iostream>#include <zmq.hpp>int main(){ zmq::context_t context(1); zmq::socket_t socket(context, zmq::socket_type::pair); int timeout_ms = 100; socket.setsockopt(ZMQ_CONNECT_TIMEOUT, timeout_ms); socket.setsockopt(ZMQ_SNDTIMEO, timeout_ms); socket.setsockopt(ZMQ_RCVTIMEO, timeout_ms); socket.connect("tcp://localhost:5555"); // send "connected" zmq::message_t msg(9); memcpy(msg.data(), "connected", 9); socket.send(msg, zmq::send_flags::none); // receive "OK" zmq::message_t incoming; auto ret = socket.recv(incoming, zmq::recv_flags::none); std::string incoming_str = incoming.to_string(); std::cout << "Received from server: " << incoming_str << std::endl; return 0;}