【QT】TCPClient客户端实例

TCPClient客户端实现功能:
(1)通过IP地址和端口号连接到服务器;
(2)采用基于行的数据通信协议,与服务器端收发消息;
(3)处理QTcpSocket的StateChange()信号,在状态栏显示socket的状态。
【QT】TCPClient客户端实例_第1张图片
1 .pro文件添加

QT += network

2 .h文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 
#include 
#include 
#include 

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
private:
    QTcpSocket *tcpClient;  //TCP通信socket
    QLabel *labSocketState;  //socket状态标签
    QString getLocalIP();  //获取本地IP

protected:
    void closeEvent(QCloseEvent *e);
    
public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_actConnected_triggered();
    void on_actDisconnected_triggered();
    void on_actClear_triggered();
    void on_actExit_triggered();
    void on_btnSend_clicked();
    void onConnected();  //connected()信号槽函数
    void onDisconnected();  //disconnected()信号槽函数
    void onSocketStateChange(QAbstractSocket::SocketState socketState);  //socketStateChange()信号槽函数,显示socket状态的变化
    void onSocketReadyRead();  //readyRead()信号槽函数,读取数据

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

3 .cpp文件

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include 

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

    tcpClient = new QTcpSocket(this);
    labSocketState = new QLabel("Socket 状态:");  //socket状态标签
    labSocketState->setMinimumWidth(250);
    ui->statusBar->addWidget(labSocketState);
    QString localIP = getLocalIP();  //获取本地IP
    this->setWindowTitle(this->windowTitle() + "----本机IP:" + localIP);  //设置窗口标题
    
    ui->cbbAddress->addItem(localIP);
    ui->actConnected->setEnabled(true);
    ui->actDisconnected->setEnabled(false);

    connect(tcpClient, &QTcpSocket::connected, this, &MainWindow::onConnected);
    connect(tcpClient, &QTcpSocket::disconnected,this, &MainWindow::onDisconnected);
    connect(tcpClient, &QTcpSocket::stateChanged, this, &MainWindow::onSocketStateChange);
    connect(tcpClient, &QTcpSocket::readyRead, this, &MainWindow::onSocketReadyRead);
}

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

void MainWindow::on_actConnected_triggered()
{
    QString addr = ui->cbbAddress->currentText();
    quint16 port = ui->spinPort->value();
    tcpClient->connectToHost(addr, port);  //连接到服务器
}

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

void MainWindow::on_actClear_triggered()
{
    ui->plainTextEdit->clear();
}

void MainWindow::on_actExit_triggered()
{
    this->close();
}

void MainWindow::on_btnSend_clicked()
{
    QString msg = ui->editMessage->text();  //获取发送数据
    ui->plainTextEdit->appendPlainText("[out] " + msg);
    ui->editMessage->clear();
    ui->editMessage->setFocus();
    QByteArray str = msg.toUtf8();
    str.append('\n');
    tcpClient->write(str);  //数据发送
}

void MainWindow::onConnected()
{
    ui->plainTextEdit->appendPlainText("**已连接到服务器");
    ui->plainTextEdit->appendPlainText("**peer address:" + tcpClient->peerAddress().toString());
    ui->plainTextEdit->appendPlainText("**peer port:" + QString::number(tcpClient->peerPort()));
    ui->actConnected->setEnabled(false);
    ui->actDisconnected->setEnabled(true);
}

void MainWindow::onDisconnected()
{
    ui->plainTextEdit->appendPlainText("**已断开与服务器的连接");
    ui->actConnected->setEnabled(true);
    ui->actDisconnected->setEnabled(false);
}

void MainWindow::onSocketStateChange(QAbstractSocket::SocketState socketState)
{
    switch(socketState)  //显示socket状态变化
    {
    case QAbstractSocket::UnconnectedState:
        labSocketState->setText("socket状态:UnconnectedState");
        break;
    case QAbstractSocket::HostLookupState:
        labSocketState->setText("socket状态:HostLookupState");
        break;
    case QAbstractSocket::ConnectingState:
        labSocketState->setText("socket状态:ConnectingState");
        break;
    case QAbstractSocket::ConnectedState:
        labSocketState->setText("socket状态:ConnectedState");
        break;
    case QAbstractSocket::BoundState:
        labSocketState->setText("socket状态:BoundState");
        break;
    case QAbstractSocket::ClosingState:
        labSocketState->setText("socket状态:ClosingState");
        break;
    case QAbstractSocket::ListeningState:
        labSocketState->setText("socket状态:ListeningState");
    }
}

void MainWindow::onSocketReadyRead()
{
    while(tcpClient->canReadLine())  //读取数据,以一整行的方式读取
        ui->plainTextEdit->appendPlainText("[in] " + tcpClient->readLine());
}

QString MainWindow::getLocalIP()
{
    QString hostName = QHostInfo::localHostName();
    QHostInfo hostInfo = QHostInfo::fromName(hostName);
    QString localIP = "";
    QList<QHostAddress> addList = hostInfo.addresses();

    if(!addList.isEmpty())
    {
        for(int i = 0; i < addList.count(); i++)
        {
            QHostAddress aHost = addList.at(i);
            if(QAbstractSocket::IPv4Protocol == aHost.protocol())
            {
                localIP = aHost.toString();
                break;
            }
        }
    }
    return localIP;
}

void MainWindow::closeEvent(QCloseEvent *e)
{
    if(tcpClient->state() == QAbstractSocket::ConnectedState)  //关闭时,确保与服务器断开连接
        tcpClient->disconnectFromHost();
    e->accept();
}

学习书籍:《Qt5.9 C++开发指南》

你可能感兴趣的:(QT学习笔记)