网络发送数据结构

根据自定义数据结构,通过网络进行发送并解析数据。

数据结构定义

#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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值