#include "networkthread.h" #include NetworkThread::NetworkThread(QObject *parent) : QObject(parent), context(1) { } void NetworkThread::connect() { socket = new zmq::socket_t(context, zmq::socket_type::pair); int linger = 0; socket->setsockopt(ZMQ_LINGER, &linger, sizeof (linger)); try { socket->bind("tcp://127.0.0.1:12345"); } catch (zmq::error_t err) { qDebug() << "failed binding socket" << err.what(); emit error(err.what()); throw; }; qDebug() << "connected"; } void NetworkThread::disconnect() { delete socket; qDebug() << "disconnected"; } void NetworkThread::reconnect() { this->disconnect(); this->connect(); } void NetworkThread::process() { connect(); while(true) { zmq::message_t response; const auto ret = socket->recv(response, zmq::recv_flags::dontwait); if(ret) { auto j = json::parse(response.to_string()); //std::cout << std::setw(4) << j << "\n\n"; if(j.contains("msg") && j["msg"].is_string()) { std::string msg_type; try { j["msg"].get_to(msg_type); } catch (nlohmann::detail::type_error& err) { qDebug() << "json type error, message type not a string: " << response.to_string().c_str(); emit error("no message type"); } if(msg_type == "request") { } else if (msg_type == "response") { try { emit httpMessage(j); } catch (nlohmann::detail::type_error& err) { qDebug() << "error reading HTTP Flow"; emit error("error converting to flow"); } } else if(msg_type == "ping") { } else { qDebug() << "unknown or broken message type received: " << msg_type.c_str(); emit error("unknown message"); } std::string m = "{\"msg\": \"ack\"}"; socket->send(zmq::buffer(m.c_str(), m.length()), zmq::send_flags::dontwait); } else { qDebug() << "broken message, but correct json: " << response.to_string().c_str(); } } } }