Qt下简单Tcp通信学习笔记

版权声明:经本人同意,方可转载。 https://blog.csdn.net/annjeff/article/details/82526609

Qt下简单Tcp通信学习笔记

Qt下Tcp通信模型

代码实现
TcpDemo


TcpDemo.pro

#-------------------------------------------------
#
# Project created by QtCreator 2018-09-07T18:33:47
#
#-------------------------------------------------

QT       += core gui
QT       += network

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = TcpDemo
TEMPLATE = app

# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0


SOURCES += \
        main.cpp \
        tcpserverwidget.cpp \
    tcpclientwidget.cpp

HEADERS += \
        tcpserverwidget.h \
    tcpclientwidget.h

FORMS += \
        tcpserverwidget.ui \
    tcpclientwidget.ui

CONFIG += C++11

tcpServerWidget.h

#ifndef TCPSERVERWIDGET_H
#define TCPSERVERWIDGET_H

#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>

namespace Ui {
class TcpServerWidget;
}

class TcpServerWidget : public QWidget
{
    Q_OBJECT

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

private slots:
    void on_btnSend_clicked();

    void on_btnClose_clicked();

private:
    Ui::TcpServerWidget *ui;
    QTcpServer *tcpServer;
    QTcpSocket *tcpSocket;
};

#endif // TCPSERVERWIDGET_H

tcpClientWidget.h

#ifndef TCPCLIENTWIDGET_H
#define TCPCLIENTWIDGET_H

#include <QWidget>
#include <QTcpSocket>

namespace Ui {
class TcpClientWidget;
}

class TcpClientWidget : public QWidget
{
    Q_OBJECT

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

private slots:
    void on_btnSend_clicked();

    void on_btnClose_clicked();

    void on_btnConnect_clicked();

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

#endif // TCPCLIENTWIDGET_H

tcpServerWidget.cpp

#include "tcpserverwidget.h"
#include "ui_tcpserverwidget.h"

TcpServerWidget::TcpServerWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TcpServerWidget)
{
    ui->setupUi(this);
    this->setWindowTitle("Server:8888");
    tcpServer = NULL;
    tcpSocket = NULL;
    //创建Tcp连接
    tcpServer = new QTcpServer(this);
    tcpServer->listen(QHostAddress::Any,8888);

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

                connect(tcpSocket,&QTcpSocket::readyRead,
                        [=]()
                        {
                            //从通信套接字中读取文字
                            QByteArray array = tcpSocket->readAll();
                            ui->textEditRead->append(array);
                        });
            }


            );

}

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

void TcpServerWidget::on_btnSend_clicked()
{
    if(tcpSocket==NULL)
    {
        return;
    }
    //获取编辑区内容
    QString str = ui->textEditWrite->toPlainText();
    //给对方发送数据,使用套接字是tcpSocket
    tcpSocket->write(str.toUtf8().data());
    ui->textEditWrite->clear();
}

void TcpServerWidget::on_btnClose_clicked()
{
    if(tcpSocket==NULL)
    {
        return;
    }
    //主动和客户端端口连接
    tcpSocket->disconnectFromHost();
    tcpSocket->close();
    tcpSocket=NULL;

}

tcpClientWidget.cpp

#include "tcpclientwidget.h"
#include "ui_tcpclientwidget.h"
#include <QHostAddress>
#include <QDebug>

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

    tcpSocket = NULL;
    //分配空间,指定父对象
    tcpSocket =new QTcpSocket(this);
    this->setWindowTitle("Client");
    connect(tcpSocket,&QTcpSocket::connected,
            [=]()
            {
               ui->textEditRead->setText("成功和服务器建立好连接");
            });
    connect(tcpSocket,&QTcpSocket::readyRead,
            [=]()
            {
                //获取对方发送的内容
                QByteArray array = tcpSocket->readAll();
                //追加到编辑区中
                ui->textEditRead->append(array);
            });
}

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

void TcpClientWidget::on_btnSend_clicked()
{
    //获取编辑区内容
    QString str = ui->textEditWrite->toPlainText();
    //发送数据
    tcpSocket->write(str.toUtf8().data());
    ui->textEditWrite->setText("");
}

void TcpClientWidget::on_btnClose_clicked()
{
    if(tcpSocket==NULL)
    {
        return;
    }
    tcpSocket->disconnectFromHost();
    tcpSocket->close();
    tcpSocket = NULL;
}

void TcpClientWidget::on_btnConnect_clicked()
{
    QString ip = ui->lineEditIp->text();
    qint16 port = ui->lineEditPort->text().toInt();
    //主动和服务器建立连接
    tcpSocket->connectToHost(QHostAddress(ip),port);
}

main.cpp

#include "tcpserverwidget.h"
#include "tcpclientwidget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    TcpServerWidget w;
    w.show();
    TcpClientWidget c;
    c.show();
    return a.exec();
}

ServerUI
这里写图片描述


ClientUi
这里写图片描述

猜你喜欢

转载自blog.csdn.net/annjeff/article/details/82526609