En esta página

QAbstractHttpServer Class

API a subclasificar para implementar un servidor HTTP. Más...

Cabecera: #include <QAbstractHttpServer>
CMake: find_package(Qt6 REQUIRED COMPONENTS HttpServer)
target_link_libraries(mytarget PRIVATE Qt6::HttpServer)
qmake: QT += httpserver
Desde: Qt 6.4
Hereda de: QObject
Heredado por:

QHttpServer

Funciones Públicas

QAbstractHttpServer(QObject *parent = nullptr)
virtual ~QAbstractHttpServer() override
(since 6.8) void addWebSocketUpgradeVerifier(const QObject *context, Handler &&func)
bool bind(QLocalServer *server)
bool bind(QTcpServer *server)
(since 6.9) QHttpServerConfiguration configuration() const
bool hasPendingWebSocketConnections() const
(since 6.8) QHttp2Configuration http2Configuration() const
QList<QLocalServer *> localServers() const
std::unique_ptr<QWebSocket> nextPendingWebSocketConnection()
QList<quint16> serverPorts() const
QList<QTcpServer *> servers() const
(since 6.9) void setConfiguration(const QHttpServerConfiguration &config)
(since 6.8) void setHttp2Configuration(const QHttp2Configuration &configuration)

Señales

Funciones protegidas

virtual bool handleRequest(const QHttpServerRequest &request, QHttpServerResponder &responder) = 0
virtual void missingHandler(const QHttpServerRequest &request, QHttpServerResponder &responder) = 0

Descripción Detallada

Subclase esta clase y anula handleRequest() y missingHandler() para crear un servidor HTTP. Utilice bind() para empezar a escuchar todas las conexiones entrantes a un servidor.

Esta es una API de bajo nivel, vea QHttpServer para una API de más alto nivel para implementar un servidor HTTP.

Documentación de las funciones miembro

[explicit] QAbstractHttpServer::QAbstractHttpServer(QObject *parent = nullptr)

Crea una instancia de QAbstractHttpServer con el padre parent.

[override virtual noexcept] QAbstractHttpServer::~QAbstractHttpServer()

Destruye una instancia de QAbstractHttpServer.

[since 6.8] template <typename Handler> void QAbstractHttpServer::addWebSocketUpgradeVerifier(const QObject *context, Handler &&func)

Añade una función de devolución de llamada func que verifica las actualizaciones entrantes de WebSocket. Se llama utilizando el objeto context proporcionado. Una actualización tiene éxito si al menos una llamada de retorno registrada devuelve Accept y ninguna llamada de retorno anterior ha devuelto Deny. Si no hay callbacks registrados, o todos devuelven PassToNext, se llama a la función missingHandler(). Las retrollamadas se ejecutan en el orden en que fueron registradas, y no pueden llamar a esta función por sí mismas.

Nota: func tiene que implementar la firma QHttpServerWebSocketUpgradeResponse (*)(const QHttpServerRequest &).

server.addWebSocketUpgradeVerifier(
        &server, [](const QHttpServerRequest &request) {
            if (request.url().path() == "/allowed"_L1)
                return QHttpServerWebSocketUpgradeResponse::accept();
            else
                return QHttpServerWebSocketUpgradeResponse::passToNext();
        });

Esta función se introdujo en Qt 6.8.

Véase también QHttpServerRequest, QHttpServerWebSocketUpgradeResponse, hasPendingWebSocketConnections(), nextPendingWebSocketConnection(), newWebSocketConnection(), y missingHandler().

bool QAbstractHttpServer::bind(QLocalServer *server)

Vincula el QLocalServer server dado, sobre el que se produce la transmisión, al servidor HTTP. Es posible llamar a esta función varias veces con diferentes instancias de server para manejar múltiples conexiones.

Después de llamar a esta función, cada nueva conexión será manejada y reenviada por el servidor HTTP.

Es responsabilidad del usuario llamar a QLocalServer::listen() en server antes de llamar a esta función. Si server no está a la escucha, no ocurrirá nada y se devolverá false.

Si el server es nullptr se devuelve false.

Si tiene éxito el server será emparentado a este servidor HTTP y se devuelve true.

Véase también QLocalServer y QLocalServer::listen().

bool QAbstractHttpServer::bind(QTcpServer *server)

Vincula el TCP server dado, sobre el que se produce la transmisión, al servidor HTTP. Es posible llamar a esta función múltiples veces con diferentes instancias de TCP server para manejar múltiples conexiones y puertos, por ejemplo conexiones SSL y no encriptadas.

Después de llamar a esta función, cada nueva conexión será manejada y reenviada por el servidor HTTP.

Es responsabilidad del usuario llamar a QTcpServer::listen() en server antes de llamar a esta función. Si server no está escuchando, no ocurrirá nada y se devolverá false.

Si tiene éxito el server será emparentado a este servidor HTTP y se devolverá true.

Para permitir el uso de HTTP 2, vincule a un QSslServer donde QSslConfiguration::setAllowedNextProtocols() ha sido llamado con los argumentos { QSslConfiguration::ALPNProtocolHTTP2 }.

Véase también QTcpServer, QTcpServer::listen(), y QSslConfiguration::setAllowedNextProtocols().

[since 6.9] QHttpServerConfiguration QAbstractHttpServer::configuration() const

Devuelve los parámetros de configuración general de este servidor.

Esta función se introdujo en Qt 6.9.

Véase también setConfiguration().

[pure virtual protected] bool QAbstractHttpServer::handleRequest(const QHttpServerRequest &request, QHttpServerResponder &responder)

Reemplaza esta función para manejar cada request entrante, examinando el request y enviando la respuesta apropiada de vuelta a responder. Devuelve true si request se ha gestionado correctamente. Si este método devuelve false, se llamará después a missingHandler().

bool QAbstractHttpServer::hasPendingWebSocketConnections() const

Devuelve true si el servidor tiene conexiones WebSocket pendientes; en caso contrario devuelve false.

Véase también newWebSocketConnection(), nextPendingWebSocketConnection() y addWebSocketUpgradeVerifier().

[since 6.8] QHttp2Configuration QAbstractHttpServer::http2Configuration() const

Devuelve los parámetros de configuración HTTP/2 del servidor.

Esta función se introdujo en Qt 6.8.

Véase también setHttp2Configuration().

QList<QLocalServer *> QAbstractHttpServer::localServers() const

Devuelve los servidores locales de este servidor HTTP.

Véase también serverPorts().

[pure virtual protected] void QAbstractHttpServer::missingHandler(const QHttpServerRequest &request, QHttpServerResponder &responder)

Sobreescriba esta función para manejar cada request entrante que no fue manejado por handleRequest(). Se llama a esta función siempre que handleRequest() devuelva false, o si hay un intento de actualización de WebSocket y no hay conexiones a newWebSocketConnection() o no hay verificadores de WebSocket que coincidan. Los parámetros request y responder son los mismos con los que se llamó a handleRequest().

Véase también handleRequest() y addWebSocketUpgradeVerifier().

[signal] void QAbstractHttpServer::newWebSocketConnection()

Esta señal se emite cada vez que una nueva conexión WebSocket está disponible.

Véase también hasPendingWebSocketConnections(), nextPendingWebSocketConnection(), y addWebSocketUpgradeVerifier().

std::unique_ptr<QWebSocket> QAbstractHttpServer::nextPendingWebSocketConnection()

Devuelve la siguiente conexión pendiente como un objeto QWebSocket conectado. Se devuelve nullptr si se llama a esta función cuando no hay conexiones pendientes.

Nota: El objeto QWebSocket devuelto no puede ser utilizado desde otro hilo.

Véase también newWebSocketConnection(), hasPendingWebSocketConnections(), y addWebSocketUpgradeVerifier().

QList<quint16> QAbstractHttpServer::serverPorts() const

Devuelve la lista de puertos en los que esta instancia de QAbstractHttpServer está escuchando.

Esta función tiene la misma garantía que QObject::children, el último servidor añadido es la última entrada del vector.

Véase también servers().

QList<QTcpServer *> QAbstractHttpServer::servers() const

Devuelve los servidores TCP y SSL desde los que este servidor HTTP gestionará las conexiones.

Véase también serverPorts().

[since 6.9] void QAbstractHttpServer::setConfiguration(const QHttpServerConfiguration &config)

Establece los parámetros de configuración general de este servidor en config.

Nota: La nueva configuración se aplicará tanto a las conexiones ya establecidas como a las siguientes.

Esta función se introdujo en Qt 6.9.

Véase también configuration().

[since 6.8] void QAbstractHttpServer::setHttp2Configuration(const QHttp2Configuration &configuration)

Establece los parámetros de configuración HTTP/2 del servidor.

La siguiente conexión HTTP/2 utilizará la dirección configuration.

Esta función se introdujo en Qt 6.8.

Véase también http2Configuration().

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.