【Qt专栏】Qt实现TCP服务端和客户端通信

文章目录

  • 前言
  • 一、TCP服务端
        • 1.项目架构
        • 2.tcpserver.h文件
        • 3.tcpserver.cpp文件
        • 4.测试效果
  • 二、TCP客户端
        • 1.项目架构
        • 2.tcpserver.h文件
        • 3.tcpserver.cpp文件
        • 4.测试效果
  • 总结


前言

网络通信是程序员必须会的一项生存技能,这里简单的实现了服务端和客户端通信的两个小示例,代码可以直接拿来用,开发环境是Qt5.9.6。


一、TCP服务端

1.项目架构

【Qt专栏】Qt实现TCP服务端和客户端通信_第1张图片

2.tcpserver.h文件
#ifndef TCPSERVER_H
#define TCPSERVER_H

#include 
//添加下面三个头文件,记得在pro文件里添加 network 模块
#include 
#include 
#include 

namespace Ui {
class TCPServer;
}

class TCPServer : public QWidget
{
    Q_OBJECT

public:
    explicit TCPServer(QWidget *parent = nullptr);
    ~TCPServer();
    void initNetwork(QString ip,quint16 port);
    void stopNetwork();

private slots:
    void    onNewConnection();//QTcpServer的newConnection()信号
    void    onConnected();	//可以不添加该接口
    void    onDisconnected();	//可以不添加该接口
    void    onSocketReadyRead();//读取socket传入的数据

    void on_pushButton_clicked();

private:
    Ui::TCPServer *ui;

    QTcpServer *tcpServer; //TCP服务器
    QTcpSocket *tcpSocket;//TCP通讯的Socket

    QString getLocalIP();//获取本机IP地址
    void    closeEvent(QCloseEvent *event);
};

#endif // TCPSERVER_H
3.tcpserver.cpp文件
#include "tcpserver.h"
#include "ui_tcpserver.h"

TCPServer::TCPServer(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TCPServer)
{
    ui->setupUi(this);
    initNetwork(getLocalIP(),55555);    //指定ip地址和监听的端口号
}

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

void TCPServer::initNetwork(QString ip, quint16 port)
{
    tcpServer=new QTcpServer(this);
    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(onNewConnection()));

    QHostAddress addr(ip);
    tcpServer->listen(addr,port);
}

void TCPServer::stopNetwork()
{
    if(tcpServer->isListening()){//tcpServer正在监听
        tcpServer->close();;//停止网络监听
    }
}

void TCPServer::onNewConnection()
{
    tcpSocket = tcpServer->nextPendingConnection(); //创建socket
    connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(onSocketReadyRead()));
    connect(tcpSocket, SIGNAL(connected()),this, SLOT(onConnected()));
    onConnected();
    connect(tcpSocket, SIGNAL(disconnected()),this, SLOT(onDisconnected()));
}

void TCPServer::onConnected()
{
    ui->plainTextEdit->appendPlainText(QStringLiteral("***客户端连接 ")
                                       +QStringLiteral("ip地址:")+tcpSocket->peerAddress().toString()
                                       +QStringLiteral(" 端口号:")+QString::number(tcpSocket->peerPort())+"***");
}

void TCPServer::onDisconnected()
{
    ui->plainTextEdit->appendPlainText(QStringLiteral("***客户端断开连接***"));
}


void TCPServer::onSocketReadyRead()
{
    while(tcpSocket->canReadLine()){
        QByteArray msg = tcpSocket->readLine();
        ui->plainTextEdit->appendPlainText("[客户端] "+msg);
    }
}

QString TCPServer::getLocalIP()
{
    QString ipString = Q_NULLPTR;
    QHostInfo hostInfo = QHostInfo::fromName(QHostInfo::localHostName());   //从本地主机名称获取主机信息
    QList<QHostAddress> listAddr = hostInfo.addresses();    //本地主机ip地址列表(IPV4/IPV6)
    foreach (auto addr, listAddr)
    {
       if((addr.isNull() == false) && (addr.protocol() == QAbstractSocket::IPv4Protocol)
               && (addr != QHostAddress::LocalHost))
       {
           ipString = addr.toString();   //根据条件筛选出本地IPV4地址
       }
    }
    return ipString;
}

void TCPServer::closeEvent(QCloseEvent *event)
{
    stopNetwork();
    event->accept();
}

void TCPServer::on_pushButton_clicked()
{
    QString msg = ui->lineEdit->text();
    ui->lineEdit->setFocus();//光标回到lineEdit
    if(msg.isEmpty())return;
    ui->lineEdit->clear();
    ui->plainTextEdit->appendPlainText("[服务端] "+msg);

    QByteArray str = msg.toUtf8();
    str.append("\n");
    tcpSocket->write(str);
}
4.测试效果

【Qt专栏】Qt实现TCP服务端和客户端通信_第2张图片

二、TCP客户端

1.项目架构

【Qt专栏】Qt实现TCP服务端和客户端通信_第3张图片

2.tcpserver.h文件
#ifndef TCPCLIENT_H
#define TCPCLIENT_H

#include 
//添加下面两个头文件,记得在pro文件里添加 network 模块
#include    
#include    

namespace Ui {
class TCPClient;
}

class TCPClient : public QWidget
{
    Q_OBJECT

public:
    explicit TCPClient(QWidget *parent = nullptr);
    ~TCPClient();
    void initNetwork(QString ip,quint16 port);
    void stopNetwork();

private slots:
//自定义槽函数
    void    onConnected();	//可以不添加该接口
    void    onDisconnected();	//可以不添加该接口
    void    onSocketReadyRead();//读取socket传入的数据

    void on_pushButton_clicked();

private:
    Ui::TCPClient *ui;
    QTcpSocket  *tcpClient;  //socket
    QString getLocalIP();//获取本机IP地址
    void    closeEvent(QCloseEvent *event);
};

#endif // TCPCLIENT_H
3.tcpserver.cpp文件
#include "tcpclient.h"
#include "ui_tcpclient.h"

TCPClient::TCPClient(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TCPClient)
{
    ui->setupUi(this);
    initNetwork(getLocalIP(),55555);    //指定服务端ip地址和的端口号
}

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

void TCPClient::initNetwork(QString ip, quint16 port)
{
    tcpClient=new QTcpSocket(this); //创建socket变量

    connect(tcpClient,SIGNAL(connected()),this,SLOT(onConnected()));
    connect(tcpClient,SIGNAL(disconnected()),this,SLOT(onDisconnected()));
    connect(tcpClient,SIGNAL(readyRead()),this,SLOT(onSocketReadyRead()));

    tcpClient->connectToHost(ip,port);
}

void TCPClient::stopNetwork()
{
    //断开与服务器的连接
    if (tcpClient->state()==QAbstractSocket::ConnectedState){
        tcpClient->disconnectFromHost();
    }
}

void TCPClient::onConnected()
{
    ui->plainTextEdit->appendPlainText("***已连接到服务器***");
}

void TCPClient::onDisconnected()
{
    ui->plainTextEdit->appendPlainText("***已断开与服务器的连接***");
}

void TCPClient::onSocketReadyRead()
{
    while(tcpClient->canReadLine()){
        QByteArray msg = tcpClient->readLine();
        ui->plainTextEdit->appendPlainText("[服务端] "+msg);
    }
}

QString TCPClient::getLocalIP()
{
    QString ipString = Q_NULLPTR;
    QHostInfo hostInfo = QHostInfo::fromName(QHostInfo::localHostName());   //从本地主机名称获取主机信息
    QList<QHostAddress> listAddr = hostInfo.addresses();    //本地主机ip地址列表(IPV4/IPV6)
    foreach (auto addr, listAddr)
    {
       if((addr.isNull() == false) && (addr.protocol() == QAbstractSocket::IPv4Protocol)
               && (addr != QHostAddress::LocalHost))
       {
           ipString = addr.toString();   //根据条件筛选出本地IPV4地址
       }
    }
    return ipString;
}

void TCPClient::closeEvent(QCloseEvent *event)
{
    stopNetwork();
    event->accept();
}

void TCPClient::on_pushButton_clicked()
{
    //发送数据
    QString  msg=ui->lineEdit->text();
    ui->lineEdit->setFocus();//光标回到lineEdit
    if(msg.isEmpty())return;
    ui->lineEdit->clear();
    ui->plainTextEdit->appendPlainText("[客户端] "+msg);

    QByteArray  str=msg.toUtf8();
    str.append('\n');
    tcpClient->write(str);
}
4.测试效果

【Qt专栏】Qt实现TCP服务端和客户端通信_第4张图片


总结

好了,两个小程序写完并可以运行进行通信,简单的实现,原理后序会专门写篇文章,这里可以直接照着上述写就OK啦,886!

你可能感兴趣的:(Qt,qt,tcp/ip,ui)