QT多线程网络通信代码
时间: 2023-03-24 17:02:42 浏览: 43
以下是一个使用Qt多线程进行网络通信的简单示例代码:
```cpp
#include <QtNetwork>
#include <QThread>
class NetworkThread : public QThread
{
Q_OBJECT
public:
NetworkThread(QObject *parent = nullptr)
: QThread(parent)
{
// 初始化网络套接字
m_socket = new QTcpSocket(this);
connect(m_socket, &QTcpSocket::readyRead, this, &NetworkThread::onReadyRead);
connect(m_socket, &QTcpSocket::disconnected, this, &NetworkThread::onDisconnected);
}
void connectToHost(const QString &host, quint16 port)
{
m_socket->connectToHost(host, port);
}
void disconnectFromHost()
{
m_socket->disconnectFromHost();
}
void sendData(const QByteArray &data)
{
m_socket->write(data);
}
signals:
void receivedData(const QByteArray &data);
void disconnected();
protected:
void run() override
{
exec();
}
private slots:
void onReadyRead()
{
QByteArray data = m_socket->readAll();
emit receivedData(data);
}
void onDisconnected()
{
emit disconnected();
}
private:
QTcpSocket *m_socket;
};
int main()
{
NetworkThread networkThread;
networkThread.connectToHost("localhost", 1234);
// 启动网络线程
networkThread.start();
// 发送数据
QByteArray data("Hello, World!");
networkThread.sendData(data);
// 停止网络线程
networkThread.disconnectFromHost();
networkThread.quit();
networkThread.wait();
return 0;
}
```
该示例中创建了一个继承自QThread的NetworkThread类,用于在后台线程中执行网络通信操作。该类中包含了一个QTcpSocket成员变量,用于与远程主机建立连接,并进行数据传输。
在main函数中,先创建了一个NetworkThread对象,并调用其connectToHost函数连接到远程主机。然后调用start函数启动该线程,在后台线程中发送数据,最后通过disconnectFromHost、quit和wait函数停止该线程。
阅读全文