嵌入式-基于qt的tcp/ip实现(2)

嵌入式-基于qt的tcp/ip实现(2)

走过路过,请帮忙点一下星星 😃

创建新界面 😮

    右键点击工程文件夹,选择add new 然后选择第二个,然后一直点即可,添加新的界面

创建ui

    首先根据设计需求,画出一个界面,从左面进行拖拽之后点击上面的排版进行排布 对每个实例进行更名与赋属性的修改 然后一个ui就创建好了

修改头文件和源码

头文件

添加套接字的头文件以及在类里面添加一个套接字对象

#ifndef CLINT_H
#define CLINT_H

#include <QWidget>
#include <QTcpSocket>//头文件
namespace Ui {
          
   
class clint;
}

class clint : public QWidget
{
          
   
    Q_OBJECT

public:
    explicit clint(QWidget *parent = 0);
    ~clint();

private slots:
    void on_B_connect__clicked();

    void on_B_disconnect__clicked();

    void on_B_close__clicked();

    void on_B_send__clicked();
    
private:
    Ui::clint *ui;

    QTcpSocket *tcpSoc_;//创建套接字对象
};

#endif // CLINT_H

源文件

    首先指针赋NULL,在没有构造的时候,如果按了send就野指针了,程序就gg 设计的时候,如果链接成功则connect字样变红;没链接就恢复默认颜色
#include "clint.h"
#include "ui_clint.h"
#include <QHostAddress>
#include <QString>
clint::clint(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::clint)
{
          
   
    ui->setupUi(this);
    setWindowTitle("clint ");


    tcpSoc_ = NULL;


    tcpSoc_ = new QTcpSocket(this);

    connect(tcpSoc_,&QTcpSocket::connected,
            [=]()
    {
          
   
            ui->B_connect_->setStyleSheet("color:red");
    }
            );

   connect(tcpSoc_,&QTcpSocket::readyRead,
           [=]()
   {
          
   

            QByteArray arr =  tcpSoc_->readAll();
            ui->E_read_->append(arr);
   }

           );

}

clint::~clint()
{
          
   
    delete ui;
}

void clint::on_B_connect__clicked()
{
          
   
    QString ip_ = ui->L_ip_->text();
    qint16 PORT_ = ui->L_port_->text().toInt();
    tcpSoc_->abort();
    tcpSoc_->connectToHost(QHostAddress(ip_), PORT_);
}

void clint::on_B_disconnect__clicked()
{
          
   
    //tcpSoc_->abort();
    tcpSoc_->disconnectFromHost();
    //tcpSoc_->disconnect();
    //tcpSoc_->close();
            ui->B_connect_->setStyleSheet("color:black");
}

void clint::on_B_close__clicked()
{
          
   
    tcpSoc_->disconnect();
    tcpSoc_->close();
    close();
}

void clint::on_B_send__clicked()
{
          
   
    //获取链接内容然后发送
    QString str = ui->E_write_->toPlainText();

    //发送数据,使用套接字tcpsocket
    tcpSoc_->write(str.toUtf8().data());

    qDebug() << str;
}
经验分享 程序员 微信小程序 职场和发展