Learn what Felgo offers to help your business succeed. Start your free evaluation today! Felgo for Your Business

QWebSocket client example


The EchoClient example implements a WebSocket client that sends a message to a WebSocket server and dumps the answer that it gets back. This example should ideally be used with the EchoServer example.


We start by connecting to the `connected()` signal.

EchoClient::EchoClient(const QUrl &url, bool debug, QObject *parent) :
    if (m_debug)
        qDebug() << "WebSocket server:" << url;
    connect(&m_webSocket, &QWebSocket::connected, this, &EchoClient::onConnected);
    connect(&m_webSocket, &QWebSocket::disconnected, this, &EchoClient::closed);

After the connection, we open the socket to the given url.

void EchoClient::onConnected()
    if (m_debug)
        qDebug() << "WebSocket connected";
    connect(&m_webSocket, &QWebSocket::textMessageReceived,
            this, &EchoClient::onTextMessageReceived);
    m_webSocket.sendTextMessage(QStringLiteral("Hello, world!"));

When the client is connected successfully, we connect to the `onTextMessageReceived()` signal, and send out "Hello, world!". If connected with the EchoServer, we will receive the same message back.

void EchoClient::onTextMessageReceived(QString message)
    if (m_debug)
        qDebug() << "Message received:" << message;

Whenever a message is received, we write it out.

Qt_Technology_Partner_RGB_475 Qt_Service_Partner_RGB_475_padded