我将qwebsocket移动到线程,然后如何在主线程中关闭它?
由于我将其移至工作人员线程,因此我无法直接从主线程拨打关闭。它随着此消息崩溃
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;
}
使用 QMetaObject::invokeMethod
:
QMetaObject::invokeMethod(mClient, "close", Qt::QueuedConnection);