QT 服务端与客户端使用案例笔记[转]

QT 服务端与客户端使用案例笔记[转]

  • 参考梅会东老师课程

目录

QT 服务端与客户端使用案例笔记

客户端

服务端

  • Qt 的两个重要信号:
    • 1、QTcpServer:newConnection:
      • 代表有新的客户端连接,调用 tcpServer 的 nextPendingConnection();
      • 直接接受,返回一个 QTcpSocket 实例
    • 2、QTcpSocket:readyRead:
      • 代表有数据发送过来,直接接收即可

客户端

#ifndef CLIENTWIDGET_H
#define CLIENTWIDGET_H

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


namespace Ui {
class ClientWidget;
}

class ClientWidget : public QWidget
{
    Q_OBJECT

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

private slots:
    void on_buttonConnect_clicked();
    void on_buttonSend_clicked();
    void on_buttonClose_clicked();

private:
    Ui::ClientWidget *ui;
    QTcpSocket * tcpSocket;//通信套接字
};

#endif // CLIENTWIDGET_H
#include "clientwidget.h"
#include "ui_clientwidget.h"
#include<QHostAddress>
#include <QDebug>
ClientWidget::ClientWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ClientWidget)
{
    ui->setupUi(this);

    //初始化套接字
    tcpSocket = NULL;

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

    //建立连接的信号槽
    connect(tcpSocket,&QTcpSocket::connected,
            [=]()
            {
                 ui->textEditRead->setText("恭喜,成功连接服务器!");
            }
            );

    //连接建立后收到服务器数据的信号槽
    connect(tcpSocket,&QTcpSocket::readyRead,
                [=]()
                {
                    //获取对方发送的内容
                    QByteArray array = tcpSocket->readAll();

                    //显示到编辑框
                    ui->textEditRead->append(array);//append,添加内容
                }
            );

    //设置窗口标题
    setWindowTitle("TCP客户端");
}

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

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

    //主动连接服务器
    tcpSocket->connectToHost(QHostAddress(ip),port);
}

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

}

void ClientWidget::on_buttonClose_clicked()
{
    //主动断开连接
    tcpSocket->disconnectFromHost();
}

服务端

#ifndef SERVEWIDGET_H
#define SERVEWIDGET_H

#include <QWidget>
#include<QTcpServer>//监听套接字
#include<QTcpSocket>//建立连接的通信套接字

namespace Ui {
class ServeWidget;
}

class ServeWidget : public QWidget
{
    Q_OBJECT

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

private slots:
    void on_ButtonSend_clicked();

    void on_ButtonClose_clicked();

private:
    Ui::ServeWidget *ui;
    QTcpServer *tcpServer;//监听套接字
    QTcpSocket *tcpSocket;//通信套接字
};

#endif // SERVEWIDGET_H
#include "servewidget.h"
#include "ui_servewidget.h"

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

    //初始化套接字
    tcpServer = NULL;
    tcpSocket = NULL;

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

    //设定端口
    ///QHostAddress::AnyIPv4, Any, AnyIPv6
    tcpServer->listen(QHostAddress::AnyIPv4, 8888); ///listen()

    //新连接建立的信号槽
    ///Qt5的Lambda表达式
    ///Qt5的connect方式(匿名函数):[= 捕获列表 &](){......}
    connect(tcpServer,&QTcpServer::newConnection,[=]() ///accept(...)
    {
        //取出建立好连接的套接字
        tcpSocket = tcpServer->nextPendingConnection();

        //获取对方的IP和端口
        QString ip = tcpSocket->peerAddress().toString();
        qint16 port = tcpSocket->peerPort();

        //将信息显示到UI
        QString temp = QString("[%1:%2]:成功连接").arg(ip).arg(port);
        ui->textEditRead->setText(temp);

        /// 注意这个connect的位置
        /// 连接建立后,读取到客户端发送过来的数据的信号槽
        connect(tcpSocket, &QTcpSocket::readyRead,
            [=]()
            {
             //从通信套接字取出内容
             QByteArray array = tcpSocket->readAll();
             //显示到UI
             ui->textEditRead->append(array);
            } );
    });
    setWindowTitle("TCP服务器,端口:8888");
}

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

void ServeWidget::on_ButtonSend_clicked()
{
    if(NULL == tcpSocket)
    {return;}

    //获取编辑区内容
    QString str = ui->textEditWrite->toPlainText();

    //给对方发数据,使用的套接字为tcpSocket
    tcpSocket->write( str.toUtf8().data() );
}

void ServeWidget::on_ButtonClose_clicked()
{
    if(NULL == tcpSocket)
    {return;}

    //主动和客户端断开连接
    tcpSocket->disconnectFromHost();

    //关闭套接字
    tcpSocket->close();
    tcpSocket = NULL;

}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值