Hi,
I’m using QTcpServer to provide a (very) lightweight html interface to my Qt desktop app. Its pretty easy to set up but I have one problem.
After receiving a readyRead() signal my socket, handleRequest, is called. This builds the HMTL page to serve and does QTcpSocket::write. Unfortunately the client (firefox in this case) does not receive the page unless I call QTcpSocket::disconnectFromHost, or close my desktop app (destructing the server).
I tried QTcpSocket::flush but this has not effect. Here’s some code:
#include <fstream>
#include <sstream>
#include <QtNetwork/QTcpSocket>
#define PORT_MIN 10000
#define PORT_MAX 10010
HelpServer::HelpServer(QObject* parent)
: QTcpServer(parent)
{
quint16 p(PORT_MIN);
while (!listen(QHostAddress::LocalHost, p) && p < PORT_MAX) {
std::cout << "HelpServer Failed to listen on port " << p << std::endl;
++p;
}
std::cout << "HelpServer Listening on port " << p << std::endl;
}
void HelpServer::incomingConnection(int socketfd)
{
QTcpSocket* client = new QTcpSocket(this); // Server is parent so owns memory on heap
client->setSocketDescriptor(socketfd);
connect(client, SIGNAL(readyRead()), this, SLOT(handleRequest()));
}
void HelpServer::handleRequest()
{
QTcpSocket* client = (QTcpSocket*)sender();
if (client->state() != QAbstractSocket::ConnectedState)
return;
QByteArray data = client->readAll();
std::string dataString(data.constData());
std::cout << "HelpServer::handleRequest" << std::endl;
std::cout << dataString << std::endl;
std::stringstream body;
body << "<html><body><h1>Hello</body></html>";
// Build response
std::string response = "HTTP/1.1 200 OK\r\n";
response.append("Content-Type: text/html\r\n");
// Separate HTML header from body
response.append("\r\n");
// Add body and terminate
response.append(body.str());
response.append("\r\n");
qint64 bytes = client->write(response.c_str()); // NOTHING SENT BY THIS ALONE
client->flush(); // HAS NO EFFECT
// client->disconnectFromHost(); // WORKS but I dont want to disconnect. I want 2 way comms via javascript.
std::cout << "HelpServer::handleRequest wrote " << bytes << " bytes:" << std::endl;
std::cout << response << std::endl;
}
↧