QT中基于TCPIP数据通信传输

客户端:
client.h

#ifndef CLIENT_H
#define CLIENT_H
#include <QTcpSocket>
#include <QObject>


class client : public QObject
{
    Q_OBJECT
public:
    explicit client(QObject *parent = nullptr);
void setAddress(QString ip);
void setPort(quint16 port);
void start();
void sendData(QByteArray data);
signals:
public slots:
private:
    QTcpSocket *tcpsocket =NULL;
    QString m_strip;
    quint16 m_port;
};
#endif // CLIENT_H

datadefine.h

#ifndef DATADEFINE_H
#define DATADEFINE_H
#include<QtGlobal>
#include<QObject>
struct head
{
    //"@@&&"
    quint8 sop[4];//头占4个字节
    //数据长度
    qint32 length;//4个字节
    //数据类型
    quint32 type;//2个字节
};
struct databuf
{
    short data[16];
};
struct str_data
{
char buffer[32];
};
#endif // DATADEFINE_H

widget.h

#ifndef WIDGET_H
#define WIDGET_H
#include "client.h"
#include <QWidget>
#include "datadefine.h"
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
    Q_OBJECT
public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();
    void init();
private slots:
    void on_connectBtn_clicked();
    void on_sendDataBtn_clicked();
    void on_sendStrBtn_clicked();
    void on_pushButton_clicked();
private:
    Ui::Widget *ui;
    client *myClient;
    head _head;
    double* dataSend;
};
#endif // WIDGET_H

cpp部分

#include "client.h"


client::client(QObject *parent) : QObject(parent)
{
    tcpsocket = new QTcpSocket;
}


void client::setAddress(QString ip)
{
    m_strip = ip;
}
void client::setPort(quint16 port)
{
    m_port = port;
}
void client::start()
{
    tcpsocket->connectToHost(m_strip,m_port);
}
void client::sendData(QByteArray data)
{
    tcpsocket->write(data);
    tcpsocket->flush();
}

#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Wi
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值