如何在线程中关闭QWebSocket?

问题描述 投票:0回答:1

我将QWebSocket移动到一个线程,然后如何在主线程中关闭它?

由于我将它移动到工作线程,我不能直接从主线程调用close。它崩溃了这条消息

QSocketNotifier:无法从另一个线程启用或禁用套接字通知程序

没有线程,它工作正常。

这是我的代码。有任何想法吗?非常感谢!

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QWebSocket>
#include <QThread>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
        Q_OBJECT

    public:
        explicit MainWindow(QWidget *parent = nullptr);
        ~MainWindow();

    private slots:
        void on_connectButton_clicked();
        void on_disconnectButton_clicked();

        void onClientConnected();
        void onClientClosed();
        void onClientTextMsg(const QString &msg);

    private:
        Ui::MainWindow *ui;
        QWebSocket *mClient;
        QThread mWorkerThread;
};

#endif // MAINWINDOW_H
#include "MainWindow.h"
#include "ui_MainWindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    mClient(nullptr)
{
    ui->setupUi(this);

    mWorkerThread.start();

    qRegisterMetaType<QAbstractSocket::SocketState>();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_connectButton_clicked()
{
    mClient = new QWebSocket();
    connect(mClient, &QWebSocket::connected, this, &MainWindow::onClientConnected, Qt::DirectConnection);
    connect(mClient, &QWebSocket::disconnected, this, &MainWindow::onClientClosed, Qt::DirectConnection);
    connect(mClient, &QWebSocket::textMessageReceived, this, &MainWindow::onClientTextMsg, Qt::DirectConnection);
    mClient->open(QUrl("ws://192.168.2.2:1936"));
    mClient->moveToThread(&mWorkerThread);
}

void MainWindow::on_disconnectButton_clicked()
{
    // FIXME crash
    // QSocketNotifier: Socket notifiers cannot be enabled or disabled from another thread
    mClient->close();
}

void MainWindow::onClientConnected() {
    qDebug() << "ws client connected";
}

void MainWindow::onClientClosed() {
    qDebug() << "ws client closed, " << mClient->closeReason() << mClient->errorString();
}

void MainWindow::onClientTextMsg(const QString &msg) {
    qDebug() << "ws recv msg:" << msg;
}
c++ qt qt5 qt-signals
1个回答
1
投票

使用QMetaObject::invokeMethod

QMetaObject::invokeMethod(mClient, "close", Qt::QueuedConnection);
© www.soinside.com 2019 - 2024. All rights reserved.