创建一个websocket连接和断开连接例程

时间:2018-10-07 20:00:43

标签: qt websocket

我正在查看一个websokect客户端的示例,但是在返回a.exe()之后我无法执行例程; 我解释说我需要执行其他例程,但是如果我不放置return a.exe();它不会建立连接,而是继续执行代码,那一定要这样做,以免发生这种情况?

#include <QtCore/QCoreApplication>
#include "sslechoclient.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

for (;;;){
    SslEchoClient client(QUrl(QStringLiteral("wss://localhost:1234")));

    Q_UNUSED(client);

//my serial reading application

}

    return a.exec();
}

Cpp

#include "sslechoclient.h"
#include <QtCore/QDebug>
#include <QtWebSockets/QWebSocket>
#include <QCoreApplication>

QT_USE_NAMESPACE

SslEchoClient::SslEchoClient(const QUrl &url, QObject *parent) :
    QObject(parent)
{
    connect(&m_webSocket, &QWebSocket::connected, this, &SslEchoClient::onConnected);
    connect(&m_webSocket, QOverload<const QList<QSslError>&>::of(&QWebSocket::sslErrors),
            this, &SslEchoClient::onSslErrors);
    m_webSocket.open(QUrl(url));
}

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

void SslEchoClient::onTextMessageReceived(QString message)
{
    qDebug() << "Message received:" << message;
    qApp->quit();
}

void SslEchoClient::onSslErrors(const QList<QSslError> &errors)
{
    Q_UNUSED(errors);

    // WARNING: Never ignore SSL errors in production code.
    // The proper way to handle self-signed certificates is to add a custom root
    // to the CA store.

    m_webSocket.ignoreSslErrors();
}

.h

#ifndef SSLECHOCLIENT_H
#define SSLECHOCLIENT_H

#include <QtCore/QObject>
#include <QtWebSockets/QWebSocket>
#include <QtNetwork/QSslError>
#include <QtCore/QList>
#include <QtCore/QString>
#include <QtCore/QUrl>

QT_FORWARD_DECLARE_CLASS(QWebSocket)

class SslEchoClient : public QObject
{
    Q_OBJECT
public:
    explicit SslEchoClient(const QUrl &url, QObject *parent = nullptr);

private Q_SLOTS:
    void onConnected();
    void onTextMessageReceived(QString message);
    void onSslErrors(const QList<QSslError> &errors);

private:
    QWebSocket m_webSocket;
};

#endif // SSLECHOCLIENT_H

如果能提供帮助,我将非常感谢。

1 个答案:

答案 0 :(得分:0)

您的应用程序是否会像这样运行:

QApplication app(argc, argv);

QWebSocket socket;
// Your stuff
int retValue = app.exec();
// Do some other stuff
return retValue;