嵌入式-基于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;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值