我在QTcpSockets和线程结合方面遇到了一些麻烦。如何使用线程Qt网络中的信号和插槽?
我想我误解了关于线程的文档,也许你可以解释我的错误在哪里。什么部分应该进入run()方法,并且当一个信号被发送并连接到线程类中的一个插槽时,它会在哪里接收?在“基地”,而不是在运行(),对不对?那么,我如何通知“正在运行”的部分,它有什么必须做的?共享对象?怎么样?
我想到底存档如下:
+-----------------------+
| Server |
| keeps some global |
| objects |
+--X----------------X---+
X X
+---------------X---+ +--X----------------+
| | | |
| Thread for Client | | Thread for Client |
| B | | A |
| keeps local data | | keeps local data |
+-----------X-------+ +-----------X-------+
X X
X X
+---------X----+ +--------X-----+
| Socket | | Socket |
+-------+---+--+ +----+---+-----+
^ | | ^
| | ---------------- | |
| | Network | |
| | --------------- | |
| | | | +----------------+
| | | | | |
| | | +-------+ Client A |
| | | | |
| | +---------->+----------------+
| |
| | +----------------+
| +------------------------------------->+ |
| | Client B |
+------------------------------------------+ |
+----------------+
下面添加代码的工作赋予“在QSocketNotifier:插座通知者不能启动或从另一个线程禁用”。我以前的方法(这里没有代码)给了“QObject:不能为不同的线程中的父项创建子项”。我也读过Events-Threads-Objects wiki文章(https://wiki.qt.io/Threads_Events_QObjects),但我想我有些东西混淆了。
我在这里需要做些什么改变,客户端A可以发送数据到服务器,服务器更改数据并将答案传递给客户端A和B(我将设置保持活动选项到实际的套接字应用程序,但出于简化原因将其留在此处)。所有“客户端”(他们的线程)必须能够从服务器读取和修改对象。这样做的最佳方法是什么?我想我应该在这里使用信号和插槽,并且自动连接应该足够好(如果所有线程都被通知一次发送数据,我可以,我的协议中有一个接收者ID,所以我可以检查消息是否应该是调用write()之前丢弃
server.pro:
QT += network
QT += core
HEADERS = \
server.h \
clientthread.h
SOURCES = \
main.cpp \
server.cpp \
clientthread.cpp
clietthead.h:
#ifndef CTHREAD_H
#define CHREAD_H
#include <QThread>
#include <QTcpSocket>
class ClientThread : public QThread {
Q_OBJECT
public:
ClientThread(int socketDescriptor, QObject *parent);
void run() Q_DECL_OVERRIDE;
QTcpSocket * tcpSocket;
public slots:
void slot_msg_answer();
void slot_request_msg_FromServer();
signals:
void error(QTcpSocket::SocketError socketError);
void signal_for_Server_request_msg();
private:
int socketDescriptor;
};
#endif
server.h
#ifndef SERVER_H
#define SERVER_H
#include <QTcpServer>
class Server : public QTcpServer {
Q_OBJECT
signals:
void signalFor_PT_msg_answert(QString);
public:
Server(QObject *parent = 0);
public slots:
void slot_request_msg();
protected:
void incomingConnection(qintptr socketDescriptor) Q_DECL_OVERRIDE;
private:
};
#endif
clientthread.cpp
#include "clientthread.h"
#include <QTcpSocket>
#include <QtNetwork>
ClientThread::ClientThread(int socketDescriptor, QObject *parent)
: QThread(parent), socketDescriptor(socketDescriptor) {
}
void ClientThread::slot_request_msg_FromServer() {
emit signal_for_Server_request_msg();
}
void ClientThread::run() {
tcpSocket = new QTcpSocket();
tcpSocket->setSocketOption(QAbstractSocket::KeepAliveOption, true);
if (!tcpSocket->setSocketDescriptor(socketDescriptor)) {
emit error(tcpSocket->error());
return;
}
QByteArray ba ("foo");
tcpSocket->write(ba);
tcpSocket->flush();
exec();
}
void ClientThread::slot_msg_answer() {
QByteArray ba ("bar");
tcpSocket->write(ba);
tcpSocket->flush();
}
的main.cpp
#include <QtCore>
#include "server.h"
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
Server server_;
if (!server_.listen(QHostAddress::Any, 1234)) {
qDebug() << "unable to start the server";
return -1;
}
return app.exec();
}
server.cpp
#include "server.h"
#include "clientthread.h"
#include <QTimer>
Server::Server(QObject *parent) : QTcpServer(parent) {
}
void Server::slot_request_msg() {
emit signalFor_PT_msg_answert("hello");
}
void Server::incomingConnection(qintptr socketDescriptor) {
ClientThread *thread = new ClientThread(socketDescriptor, this);
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
connect(this, &Server::signalFor_PT_msg_answert, thread , &ClientThread::slot_msg_answer);
connect(thread, &ClientThread::signal_for_Server_request_msg, this, &Server::slot_request_msg);
thread->start();
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), thread, SLOT(slot_msg_answer()));
timer->start(2000);
}
所有上面的代码是基于Qt的螺纹时运服务器的例子,这是在BSD授权:
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
你有看过这个吗? http://doc.qt.io/qt-5/threads-qobject.html特别是带有事件循环的部分。 – Hayt
是的,我读过它,并理解它使用“exec();”在“run()”中启动线程的“本地”事件回调,并且不在“connect(...);”上使用显式连接类型使qt自己选择正确的连接(默认:qtautoconnection)。 – user2567875
'QThread'更像是一个线程控制器,所以除非你想改变Qt管理线程的方式,否则你最好不要继承它。 [本文](https://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/)描述了一种很好的方法, QThread'。 – TheDarkKnight