如何在线程中关闭QWebSocket?

时间:2019-03-05 07:32:40

标签: c++ qt qt5 qt-signals

我将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;
}

1 个答案:

答案 0 :(得分:1)

使用QMetaObject::invokeMethod

QMetaObject::invokeMethod(mClient, "close", Qt::QueuedConnection);