Skip to content

QTcpServer

ModuleNetwork
Include
#include <QCoroTcpServer>
CMake
target_link_libraries(myapp QCoro::Network)
QMake
QT += QCoroNetwork

QTcpServer really only has one asynchronous operation worth co_awaiting, and that's waitForNewConnection().

Since QTcpServer doesn't provide the ability to co_await those operations, QCoro provides a wrapper class QCoroTcpServer. To wrap a QTcpServer object into the QCoroTcpServer wrapper, use qCoro():

QCoroTcpServer qCoro(QTcpServer &);
QCoroTcpServer qCoro(QTcpServer *);

waitForNewConnection()

Waits until a new incoming connection is available or until it times out. Returns pointer to QTcpSocket or nullptr if the operation timed out or another error has occured.

If the timeout is -1 the operation will never time out.

See documentation for QTcpServer::waitForNewConnection() for details.

QCoro::Task<QTcpSocket *> QCoroTcpServer::waitForNewConnection(int timeout_msecs = 30'000);
QCoro::Task<QTcpSocket *> QCoroTcpServer::waitForNewConnection(std::chrono::milliseconds timeout);

Examples

#include <QCoroTcpServer>

QCoro::Task<> runServer(uint16_t port) {
    QTcpServer server;
    server.listen(QHostAddress::LocalHost, port);

    while (server.isListening()) {
        auto *socket = co_await qCoro(server).waitForNewConnection(10s);
        if (socket != nullptr) {
            newClientConnection(socket);
        }
    }
}