QT怎么接收C语言TCP服务器发送过来的结构体
时间: 2024-04-06 07:09:53 浏览: 91
QT TCP客户端在子线程中发送结构体数据和接收信息普通数据信息
在QT中,可以使用QTcpSocket类来接收C语言TCP服务器发送过来的结构体数据。具体步骤如下:
1. 创建QTcpSocket对象
```c++
QTcpSocket *socket = new QTcpSocket(this);
```
2. 连接到C语言TCP服务器
```c++
socket->connectToHost("127.0.0.1", 8888);
```
3. 接收数据
```c++
char buffer[sizeof(MyStruct)];
socket->read(buffer, sizeof(MyStruct));
MyStruct *data = reinterpret_cast<MyStruct*>(buffer);
```
注意,需要根据结构体的大小来定义接收缓冲区的大小,并使用reinterpret_cast将接收到的数据转换为结构体类型。
完整的代码示例:
```c++
#include <QTcpSocket>
struct MyStruct {
int a;
double b;
char c[20];
};
class TcpClient : public QObject
{
Q_OBJECT
public:
TcpClient(QObject *parent = nullptr) : QObject(parent) {
QTcpSocket *socket = new QTcpSocket(this);
socket->connectToHost("127.0.0.1", 8888);
connect(socket, &QTcpSocket::readyRead, this, [=]() {
char buffer[sizeof(MyStruct)];
socket->read(buffer, sizeof(MyStruct));
MyStruct *data = reinterpret_cast<MyStruct*>(buffer);
qDebug() << "Received:" << data->a << data->b << data->c;
});
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
TcpClient client(&a);
return a.exec();
}
```
阅读全文