Qt知识点梳理 —— TCP通信实现

19 篇文章 3 订阅

文章目录

系统结构

执行效果

项目源码

客户端

服务端

开发环境


系统结构

分别建立服务端与客户端,系统运行后启动服务端,并建立起一个客户端,如图:

执行效果

项目源码

若要使用Qt套接字,需要在项目.pro文件(本例为:012_TCP.pro)中加入

QT += network

客户端

ClientWidget.h

#ifndef CLIENTWIDGET_H
#define CLIENTWIDGET_H

#include <QWidget>
#include <QTcpSocket>//通信套接字
#include <QHostAddress>

namespace Ui {
class ClientWidget;
}

class ClientWidget : public QWidget
{
    Q_OBJECT

public:
    explicit ClientWidget(QWidget *parent = nullptr);
    ~ClientWidget();

private slots:
    void on_btn_connect_clicked();
    void on_btn_send_clicked();
    void on_btn_close_clicked();

private:
    Ui::ClientWidget *ui;
    QTcpSocket *tcpSocket;
};

#endif // CLIENTWIDGET_H

ClientWidget.cpp

#include "clientwidget.h"
#include "ui_clientwidget.h"


ClientWidget::ClientWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ClientWidget)
{
    ui->setupUi(this);

    tcpSocket = NULL;
    //分配空间 指定父对象
    tcpSocket = new QTcpSocket(this);

    setWindowTitle(QStringLiteral("客户端"));

    connect(tcpSocket,&QTcpSocket::connected,
        [=]()
        {
            ui->tb_read->setText(QStringLiteral("成功与服务端建立连接"));
        }
        );

    connect(tcpSocket,&QTcpSocket::readyRead,
        [=]()
        {
            //获取对方发送的内容
            QByteArray array=tcpSocket->readAll();
            ui->tb_read->append(array);
        }
        );

}

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

void ClientWidget::on_btn_connect_clicked()
{
    //获取服务器IP和端口
    QString ip = ui->tb_ip->text();
    qint16 port = ui->tb_port->text().toInt();

    tcpSocket->connectToHost(QHostAddress(ip),port);
}

void ClientWidget::on_btn_send_clicked()
{
    //获取编辑框内容
    QString str=ui->tb_write->toPlainText();
    //发射数据
    tcpSocket->write(str.toUtf8().data());
}

void ClientWidget::on_btn_close_clicked()
{
    //主动和对方断开连接
    tcpSocket->disconnectFromHost();
}

服务端

ServerWidget.h

#ifndef SERVERWIDGET_H
#define SERVERWIDGET_H

#include <QWidget>
#include <QTcpServer> //监听套接字
#include <QTcpSocket> //通信套接字

QT_BEGIN_NAMESPACE
namespace Ui { class ServerWidget; }
QT_END_NAMESPACE

class ServerWidget : public QWidget
{
    Q_OBJECT

public:
    ServerWidget(QWidget *parent = nullptr);
    ~ServerWidget();

private slots:
    void on_btn_send_clicked();

    void on_btn_close_clicked();

private:
    Ui::ServerWidget *ui;
    QTcpServer *tcpServer;
    QTcpSocket *tcpSocket;

};
#endif // SERVERWIDGET_H
ServerWidget.cpp
#include "serverwidget.h"
#include "ui_serverwidget.h"


ServerWidget::ServerWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::ServerWidget)
{
    ui->setupUi(this);

    tcpServer=NULL;
    tcpSocket=NULL;

    //监听套接字 指定父对象 让其自动回收空间
    tcpServer = new QTcpServer(this);

    tcpServer->listen(QHostAddress::Any,8888);

    setWindowTitle(QStringLiteral("服务端,端口:8888"));

    connect(tcpServer, &QTcpServer::newConnection,
        [=]()
        {
            //取出建立好连接的套接字
            tcpSocket = tcpServer->nextPendingConnection();
            //获取对方的IP和端口
            QString ip = tcpSocket->peerAddress().toString();
            qint16 port = tcpSocket->peerPort();
            QString temp=QStringLiteral("[%1,:%2]:成功连接").arg(ip).arg(port);
            ui->tb_read->setText(temp);

            //收到客户端数据
            connect(tcpSocket,&QTcpSocket::readyRead,
                [=]()
                {
                    QByteArray array=tcpSocket->readAll();
                    ui->tb_read->append(array);
                }
                );
        }
        );


}

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


void ServerWidget::on_btn_send_clicked()
{
    if(tcpSocket == NULL)
    {
        return;
    }
    //获取编辑区内容
    QString str = ui->tb_write->toPlainText();
    tcpSocket->write(str.toUtf8().data());
}

void ServerWidget::on_btn_close_clicked()
{
    if(tcpSocket ==NULL)
    {
        return;
    }
    //主动和客户端断开连接
    tcpSocket->disconnectFromHost();
    tcpSocket->close();
}

main.cpp

#include "serverwidget.h"

#include <QApplication>
#include "clientwidget.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    ServerWidget w;
    w.show();//启动一个服务端

    ClientWidget w2;
    w2.show();//启动一个客户端

    return a.exec();
}

GitHub地址:lizhifun/QtTCP

开发环境

Author:Lizhifun

OS:Windows 10 家庭中文版

Compiler:Microsoft Visual C++ Compiler 15.9.28307.1259(amd64)

Kit:Desktop Qt 5.14.2 MSVC2017 64bit

Qt Creator:4.11.1

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lizhifun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值