65 lines
1.1 KiB
C++
65 lines
1.1 KiB
C++
|
#include "ZMQServer.h"
|
||
|
|
||
|
#include <QCoreApplication>
|
||
|
#include <QByteArray>
|
||
|
|
||
|
#include "MainWindow.h"
|
||
|
|
||
|
ZMQServer::ZMQServer(QObject* param)
|
||
|
: QThread(param)
|
||
|
, ctx_()
|
||
|
, socket_(ctx_, zmq::socket_type::pull){
|
||
|
}
|
||
|
|
||
|
bool ZMQServer::Start(quint16 port) {
|
||
|
qDebug() << "NetClient::Start listen port=" << port;
|
||
|
if (!stop_) {
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
stop_ = false;
|
||
|
port_ = port;
|
||
|
start();
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
void ZMQServer::Stop() {
|
||
|
//m_udpSocket->close();
|
||
|
stop_ = true;
|
||
|
try {
|
||
|
socket_.close();
|
||
|
ctx_.close();
|
||
|
}
|
||
|
catch (const std::exception&) {
|
||
|
|
||
|
}
|
||
|
|
||
|
wait();
|
||
|
}
|
||
|
|
||
|
void ZMQServer::run() {
|
||
|
std::string host = "tcp://0.0.0.0:" + std::to_string(port_);
|
||
|
socket_.bind(host);
|
||
|
while (!stop_) {
|
||
|
zmq::message_t request;
|
||
|
try {
|
||
|
//char buffer[256] = { 0 };
|
||
|
auto ok = socket_.recv(request, zmq::recv_flags::none);
|
||
|
if (ok) {
|
||
|
QByteArray buffer(reinterpret_cast<char*>(request.data()), (int)request.size());
|
||
|
QString message(buffer);
|
||
|
emit MessageReady(message);
|
||
|
zmq::message_t reply(2);
|
||
|
memcpy(reply.data(), "ok", 2);
|
||
|
socket_.send(reply);
|
||
|
}
|
||
|
}
|
||
|
catch (const std::exception&) {
|
||
|
|
||
|
}
|
||
|
|
||
|
|
||
|
}
|
||
|
|
||
|
//socket_.unbind(host);
|
||
|
}
|