根据自定义数据结构,通过网络进行发送并解析数据。
数据结构定义
#ifndef TYPE_H
#define TYPE_H
struct NetDataHeader {
int DataType;
int DataSize;
};
struct NetDataBase {
NetDataHeader dataHeader;
double data1;
double data2;
double data3;
};
#endif // TYPE_H
实现部分
#include "Widget.h"
#include "ui_Widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
mySocket = new QTcpSocket();
QObject::connect(mySocket, &QTcpSocket::readyRead, this, &Widget::MySocketReadData);
QObject::connect(mySocket, &QTcpSocket::disconnected, this, &Widget::MySocketDisconnected);
ui->sendButton->setEnabled(false);
ui->IP->setText("127.0.0.1");
ui->port->setText("5000");
}
Widget::~Widget()
{
delete mySocket;
delete ui;
}
void Widget::MySocketReadData()
{
QByteArray buffer;
buffer = mySocket->readAll();
NetDataBase myData;
if(!buffer.isEmpty()) {
char *src = buffer.data();
memcpy(&myData, src, sizeof(NetDataBase));
ui->recvText->setText(QString("data1:%1,data2:%2,data3:%3")
.arg(myData.data1)
.arg(myData.data2)
.arg(myData.data3));
}
}
void Widget::MySocketDisconnected()
{
ui->sendButton->setEnabled(false);
ui->connectButton->setText("连接");
qDebug()<<"Disconnected!";
}
void Widget::on_sendButton_clicked()
{
NetDataBase myData;
// myData.dataHeader.DataSize = 1;
myData.dataHeader.DataSize = sizeof(NetDataBase) - sizeof(NetDataHeader);
myData.data1 = -1.234567890;
myData.data2 = 1.234567890;
myData.data3 = 30.1;
QByteArray data;
data.resize(sizeof(NetDataBase));
memcpy(data.data(), &myData, sizeof(NetDataBase));
mySocket->write(data);
mySocket->flush();
}
void Widget::on_connectButton_clicked()
{
if(ui->connectButton->text() == tr("连接"))
{
QString ip;
int port;
ip = ui->IP->text();
port = ui->port->text().toInt();
mySocket->abort();
mySocket->connectToHost(ip, port);
if(!mySocket->waitForConnected(30000)) {
qDebug()<<"Connection failed!";
return;
}
qDebug()<<"Connect successfully!";
ui->sendButton->setEnabled(true);
ui->connectButton->setText("断开连接");
} else
{
mySocket->disconnectFromHost();
ui->connectButton->setText("连接");
ui->sendButton->setEnabled(false);
}
}