QTcpSocket/QTcpServer always reading empty



  • I'm trying to run a basic HTTP server in Qt. I can write HTTP headers and HTML back to the browser, but I can't receive any headers from the browser. Any read operation returns nothing and functions like "bytesAvailable()" always return 0.

    This is my .h file:

    #ifndef HTTPSERVER2_H
    #define HTTPSERVER2_H
    
    #include <QTcpServer>
    #include <QObject>
    
    class HTTPServer2 : public QObject
    {
        Q_OBJECT
    public:
        explicit HTTPServer2(QObject *parent = 0);
    
    signals:
    
    public slots:
    
    private:
        QTcpServer *server;
    
    private slots:
        void readRequest();
    };
    
    #endif // HTTPSERVER2_H
    

    And this is my .cpp file:

    #include <QDebug>
    #include <QTcpServer>
    #include <QTcpSocket>
    #include "httpserver2.h"
    
    HTTPServer2::HTTPServer2(QObject *parent) : QObject(parent) {
        int port = 5000;
    
        server = new QTcpServer();
    
        if (server->listen(QHostAddress::Any, port)) {
            QString portStr = QString::number(port);
            qDebug() << "Server running on port " + portStr;
    
            connect(server, SIGNAL(newConnection()), this, SLOT(readRequest()));
        } else {
            qDebug() << "Failed to create server: " + server->serverError();
        }
    }
    
    void HTTPServer2::readRequest() {
        QTcpSocket* client = server->nextPendingConnection();
    
        QByteArray ba = client->readAll();
        QString str = ba.data();
    
        QString response = "Hello world";
        client->write("HTTP/1.1 200 OK\r\n");
        client->write("Server: Qt Web Server\r\n");
        client->write("Content-Type: text/html; charset=utf-8\r\n");
        QString responseLength = "Content-Length: " + QString::number(response.length()) + "\r\n";
        client->write(responseLength.toUtf8());
        client->write("Connection: close\r\n");
        client->write("\r\n");
        client->write(response.toUtf8());
    
        client->disconnect();
    }
    

    I've gotten an HTTP server to work in Java before, but I've been struggling to get this working for quite some time. Any help would be very much appreciated.


  • Moderators

    Hi @slimac55 and Welcome,
    You should connect to readyRead signal once you get the new connection and then read the data in the slot.



  • Thanks, I got it with that. For reference, I also used waitForReadyRead() to help debugging it all.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.