用qt写一段代码实现同一个socket通讯创建两个独立的线程或进程,一个用于从socket接收特征值数据,另一个用于从socket接收实时波形数据
时间: 2023-08-13 09:04:53 浏览: 92
用Qt做的Socket通讯程序
5星 · 资源好评率100%
以下是用Qt实现创建两个独立线程通讯的示例代码:
```cpp
#include <QCoreApplication>
#include <QTcpSocket>
#include <QThread>
#include <QDebug>
class FeatureThread : public QThread
{
Q_OBJECT
public:
explicit FeatureThread(QObject *parent = nullptr) : QThread(parent)
{
m_socket = new QTcpSocket(this);
}
signals:
void featureDataReceived(const QByteArray& data);
protected:
void run() override
{
m_socket->connectToHost("127.0.0.1", 1234);
if(m_socket->waitForConnected())
{
while(true)
{
if(m_socket->waitForReadyRead())
{
QByteArray data = m_socket->readAll();
emit featureDataReceived(data);
}
}
}
else
{
qDebug() << "Failed to connect to host";
}
}
private:
QTcpSocket* m_socket;
};
class WaveformThread : public QThread
{
Q_OBJECT
public:
explicit WaveformThread(QObject *parent = nullptr) : QThread(parent)
{
m_socket = new QTcpSocket(this);
}
signals:
void waveformDataReceived(const QByteArray& data);
protected:
void run() override
{
m_socket->connectToHost("127.0.0.1", 5678);
if(m_socket->waitForConnected())
{
while(true)
{
if(m_socket->waitForReadyRead())
{
QByteArray data = m_socket->readAll();
emit waveformDataReceived(data);
}
}
}
else
{
qDebug() << "Failed to connect to host";
}
}
private:
QTcpSocket* m_socket;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
FeatureThread featureThread;
WaveformThread waveformThread;
QObject::connect(&featureThread, &FeatureThread::featureDataReceived, [](const QByteArray& data){
qDebug() << "Received feature data: " << data;
});
QObject::connect(&waveformThread, &WaveformThread::waveformDataReceived, [](const QByteArray& data){
qDebug() << "Received waveform data: " << data;
});
featureThread.start();
waveformThread.start();
return a.exec();
}
#include "main.moc"
```
这段代码创建了两个独立的线程 `FeatureThread` 和 `WaveformThread`,分别用于接收特征值数据和实时波形数据。在每个线程中,使用 `QTcpSocket` 连接到指定的主机和端口,并在接收到数据时发射信号。在主函数中,将接收到的数据通过连接到相应的信号槽来处理。
注意,这里简化了线程的退出逻辑。在实际应用中,需要考虑线程的安全退出。
阅读全文