Web: support synchronous TCP/IP communication

This commit is contained in:
wmayer
2021-10-14 15:07:05 +02:00
parent 0e7314068c
commit 39e02ca195
3 changed files with 29 additions and 16 deletions

View File

@@ -26,6 +26,7 @@
#include <QCoreApplication>
#include <QTcpSocket>
#include <stdexcept>
#include <memory>
#include "Server.h"
#include <Base/Exception.h>
@@ -109,8 +110,9 @@ const QByteArray& ServerEvent::request() const
// ----------------------------------------------------------------------------
AppServer::AppServer(QObject* parent)
AppServer::AppServer( bool direct, QObject* parent)
: QTcpServer(parent)
, direct(direct)
{
PyObject* mod = PyImport_ImportModule("__main__");
if (mod) {
@@ -127,6 +129,7 @@ void AppServer::incomingConnection(qintptr socket)
connect(s, SIGNAL(readyRead()), this, SLOT(readClient()));
connect(s, SIGNAL(disconnected()), this, SLOT(discardClient()));
s->setSocketDescriptor(socket);
addPendingConnection(s);
}
void AppServer::readClient()
@@ -134,7 +137,13 @@ void AppServer::readClient()
QTcpSocket* socket = (QTcpSocket*)sender();
if (socket->bytesAvailable() > 0) {
QByteArray request = socket->readAll();
QCoreApplication::postEvent(this, new ServerEvent(socket, request));
std::unique_ptr<ServerEvent> event(std::make_unique<ServerEvent>(socket, request));
if (direct) {
customEvent(event.get());
}
else {
QCoreApplication::postEvent(this, event.release());
}
}
// if (socket->state() == QTcpSocket::UnconnectedState) {
// //mark the socket for deletion but do not destroy immediately
@@ -154,6 +163,15 @@ void AppServer::customEvent(QEvent* e)
QByteArray msg = ev->request();
QTcpSocket* socket = ev->socket();
std::string str = handleRequest(msg);
socket->write(str.c_str());
if (direct)
socket->waitForBytesWritten();
socket->close();
}
std::string AppServer::handleRequest(QByteArray msg)
{
std::string str;
if (msg.startsWith("GET ")) {
msg = QByteArray("GET = ") + msg.mid(4);
@@ -166,8 +184,7 @@ void AppServer::customEvent(QEvent* e)
str = runPython(msg);
}
socket->write(str.c_str());
socket->close();
return str;
}
std::string AppServer::getRequest(const std::string& str) const