【QT】TCP通信(QTcpServer 和 QTcpSocket)

1. TCP通信概述

TCP是一种被大多数Internet网络协议(如HTTP)用于数据传输的低级网络协议,它是可靠的、面向流、面向连接的传输协议,特别适合于连续数据传输。

TCP通信必须先建立TCP连接,分为服务器端和客户端。
Qt提供QTcpServer类和QTcpSocket类用于建立TCP通信。
服务器端必须使用QTcpServer用于端口监听,建立服务器;QTcpSocket用于建立连接后使用套接字进行通信。

2. QTcpServer

QTcpServer继承于QObject

2.1 公共函数

void close() 关闭服务器,停止网络监听

bool listen(address, port) 在给定IP地址和端口上开始监听,若成功返回true。address = QHostAddress addr(IP)

bool isListening() 返回true表示服务器处于监听状态

QTcpSocket* nextPendingConnection() 返回下一个等待接入的连接。套接字是作为服务器的子节点创建的,这意味着当QTcpServer对象被销毁时,它将被自动删除。在使用完对象后显式地删除它,以避免浪费内存。如果在没有挂起连接时调用此函数,则返回0。注意:返回的QTcpSocket对象不能从其他线程使用。如果您想使用来自另一个线程的传入连接,则需要重写incomingConnection()。

QHostAddress serverAddress() 若服务器处于监听状态,返回服务器地址

quint16 serverPort() 若服务器处于监听状态,返回服务器监听端口

bool waitForNewConnection() 以阻塞的方式等待新的连接

2.2 信号

void acceptError(QAbstractSocket::SocketError socketError) 当接受一个新的连接发生错误时发射此信号,参数socketError描述了错误信息

void newConnection() 当有新的连接时发射此信号

2.3 保护函数

void incomingConnection(qintptr socketDescriptor) 当有新的连接可用时,QTcpServer内部调用此函数,创建一个QTcpServer对象,添加到内部可用新连接列表,然后发射newConnection()信号。用户若从QTcpServer继承定义类,可以重定义此函数,但必须调用addPendingConnection()。qintptr根据系统类型不同而不同,32位为qint32,64位为qint64。

void addPendingConnection(QTcpSocket* socket) 由incomingConnection()调用,将创建的QTcpSocket添加到内部新可用连接列表。

3. QTcpSocket

QTcpSocket是从QIODevice间接继承的

QIODevice -> QAbstractSocket -> QTcpSocket

QTcpSocket类除了构造和析构,其他函数都是从QAbstractSocket继承或重定义的

3.1 公共函数

void connectToHost(QHostAddress& address, quint16 port) 以异步方式连接到指定IP地址和端口的TCP服务器,连接成功会发送connected()信号

void disconnectFromHost() 断开socket,关闭成功后会发射disconnected()信号

bool waitForConnected() 等待直到建立socket连接

bool waitForDisconnected() 等待直到断开socket连接

QHostAddress localAddress() 返回本socket的地址

quint16 localPort 返回本socket的端口

QHostAddress peerAddress() 在已连接状态下,返回对方socket的地址

QString peerName() 返回connectToHost()连接到的对方的主机名

quint16 peerPort() 在已连接状态下,返回对方socket的端口

qint64 readBufferSize() 返回内部读取缓冲区的大小,该大小决定了read()和realAll()函数能读出的数据的大小

void setReadBufferSize(qint64 size) 设置内部读取缓冲区的大小

qint64 bytesAvailable() 返回需要读取的缓冲区的数据的字节数

bool canReadLine() 如果有行数据要从socket缓冲区读取,则返回true

SocketState state() 返回socket当前的状态

3.2 信号

void connected() connectToHost()成功连接到服务器后会发射此信号

void disconnected() 断开socket连接后会发射此信号

void error(QAbstractSocket::SocketError socketError) 当socket发生错误时会发射此信号

void hostFound() 调用connectToHost()找到主机后会发射此信号

void stateChanged(QAbstractSocket::SocketState socketState) 当socket状态发生变化时会发射此信号,参数socketState表示socket当前的状态

void readyRead() 当缓冲区有新数据需要读取时会发射此信号,在此信号的槽函数里读取缓冲区的数据

4. 代码示例

4.1 服务器端

使用Qt网络模块,需要在配置文件.pro中添加:

Qt += network

MainWindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QAction>
#include <QCloseEvent>
#include <QComboBox>
#include <QGridLayout>
#include <QHostInfo>
#include <QLabel>
#include <QLineEdit>
#include <QMainWindow>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <QPushButton>
#include <QSpinBox>
#include <QTcpServer>
#include <QTcpSocket>

namespace Ui {
    class MainWindow;
}

class MainWindow : public QMainWindow {
    Q_OBJECT

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

protected:
    void closeEvent(QCloseEvent* event);

private slots:
    //工具栏按钮
    void slotActStartTriggered();
    void slotActStopTriggered();
    void slotActClearTriggered();
    void slotActQuitTriggered();

    //界面按钮
    void slotBtnSendClicked();

    //自定义槽函数
    void slotNewConnection();       // QTcpServer的newConnection()信号
    void slotClientConnected();     //客户端socket连接
    void slotClientDisconnected();  //客户端socket断开连接
    void slotSocketStateChange(QAbstractSocket::SocketState socketState);
    void slotSocketReadyRead();  //读取socket传入的数据

private:
    Ui::MainWindow* ui;

    QAction* m_pActStartListen;
    QAction* m_pActStopListen;
    QAction* m_pActClearText;
    QAction* m_pActQuit;
    QWidget* m_pCentralWidget;
    QGridLayout* m_pGridLayout;
    QLabel* m_pLabel1;
    QComboBox* m_pComBoxIP;
    QLabel* m_pLabel2;
    QSpinBox* m_pSpinBoxPort;
    QLineEdit* m_pLineEdit;
    QPushButton* m_pBtnSend;
    QPlainTextEdit* m_pPlainText;
    QLabel* m_pLabListenStatus;  //状态栏标签
    QLabel* m_pLabSocketState;   //状态栏标签
    QTcpServer* m_pTcpServer;    // TCP服务器
    QTcpSocket* m_pTcpSocket;    // TCP通信的socket

    QString getLocalIP();  //获取本机IP地址
};

#endif  // MAINWINDOW_H

MainWindow.cpp

#include "mainwindow.h"

#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
    ui->setupUi(this);
    this->setWindowTitle(QStringLiteral("TCP服务端"));
    ui->menuBar->hide();

    //工具栏
    ui->mainToolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);  //设置工具栏显示风格(图标在上文字在下)
    m_pActStartListen = new QAction(QIcon(":/new/prefix1/res/开始.png"), QStringLiteral("开始监听"), this);
    m_pActStopListen = new QAction(QIcon(":/new/prefix1/res/暂停.png"), QStringLiteral("停止监听"), this);
    m_pActClearText = new QAction(QIcon(":/new/prefix1/res/清空数据.png"), QStringLiteral("清空文本框"), this);
    m_pActQuit = new QAction(QIcon(":/new/prefix1/res/退出.png"), QStringLiteral("退出"), this);
    ui->mainToolBar->addAction(m_pActStartListen);
    ui->mainToolBar->addAction(m_pActStopListen);
    ui->mainToolBar->addAction(m_pActClearText);
    ui->mainToolBar->addSeparator();
    ui->mainToolBar->addAction(m_pActQuit);

    //界面布局
    m_pCentralWidget = new QWidget(this);
    m_pGridLayout = new QGridLayout(m_pCentralWidget);
    m_pLabel1 = new QLabel(QStringLiteral("监听地址"), m_pCentralWidget);  //父对象为新的widget
    // label对象被析构了,所以不会在界面显示。label1需要作为成员变量才可显示或者用指针
    //    QLabel label1;
    //    label1.setText("监听地址");
    m_pComBoxIP = new QComboBox(m_pCentralWidget);
    // m_pComBoxIP->addItem("192.168.1.104");  // QComboBox设置默认项必须添加项
    //必须先add项才能操作下面
    //    comBoxAddr->setCurrentIndex(0);
    //    comBoxAddr->setCurrentText("192.168.1.104");
    m_pLabel2 = new QLabel(QStringLiteral("监听端口"), m_pCentralWidget);
    m_pSpinBoxPort = new QSpinBox(m_pCentralWidget);
    m_pSpinBoxPort->setMinimum(1);
    m_pSpinBoxPort->setMaximum(65535);  //端口范围1~65535
    m_pLineEdit = new QLineEdit(m_pCentralWidget);
    m_pBtnSend = new QPushButton(QStringLiteral("发送消息"), m_pCentralWidget);
    m_pPlainText = new QPlainTextEdit(m_pCentralWidget);
    m_pGridLayout->addWidget(m_pLabel1, 0, 0, Qt::AlignRight);
    // GLayout->addWidget(&label1, 0, 0, Qt::AlignRight);  //对象可以用&的方式
    m_pGridLayout->addWidget(m_pComBoxIP, 0, 1, 1, 2);
    m_pGridLayout->addWidget(m_pLabel2, 0, 3, Qt::AlignRight);
    m_pGridLayout->addWidget(m_pSpinBoxPort, 0, 4);
    m_pGridLayout->addWidget(m_pLineEdit, 1, 0, 1, 4);
    m_pGridLayout->addWidget(m_pBtnSend, 1, 4);
    m_pGridLayout->addWidget(m_pPlainText, 2, 0, 5, 5);
    this->setCentralWidget(m_pCentralWidget);

    //状态栏
    m_pLabListenStatus = new QLabel(QStringLiteral("监听状态:"));
    m_pLabListenStatus->setMinimumWidth(150);
    ui->statusBar->addWidget(m_pLabListenStatus);
    m_pLabSocketState = new QLabel(QStringLiteral("Socket状态:"));
    m_pLabSocketState->setMinimumWidth(200);
    ui->statusBar->addWidget(m_pLabSocketState);

    QString localIP = getLocalIP();
    this->setWindowTitle(this->windowTitle() + "---本机IP:" + localIP);
    m_pComBoxIP->addItem(localIP);

    m_pTcpServer = new QTcpServer(this);
    connect(m_pTcpServer, &QTcpServer::newConnection, this, &MainWindow::slotNewConnection);

    connect(m_pActStartListen, &QAction::triggered, this, &MainWindow::slotActStartTriggered);
    connect(m_pActStopListen, &QAction::triggered, this, &MainWindow::slotActStopTriggered);
    connect(m_pBtnSend, &QPushButton::clicked, this, &MainWindow::slotBtnSendClicked);
    connect(m_pActClearText, &QAction::triggered, this, &MainWindow::slotActClearTriggered);
    connect(m_pActQuit, &QAction::triggered, this, &MainWindow::slotActQuitTriggered);
}

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

void MainWindow::closeEvent(QCloseEvent* event) {
	//关闭窗口时停止监听
    if (m_pTcpServer->isListening())
        m_pTcpServer->close();  //停止网络监听
    QMessageBox::StandardButton button = QMessageBox::question(this, QStringLiteral(""), "是否退出?");
    if (button == QMessageBox::StandardButton::Yes) {
        event->accept();
    } else {
        event->ignore();
    }
}

void MainWindow::slotActStartTriggered() {
    //开始监听
    QString IP = m_pComBoxIP->currentText();
    quint16 port = m_pSpinBoxPort->value();
    QHostAddress addr(IP);
    m_pTcpServer->listen(addr, port);  //开始监听
    // m_pTcpServer->listen(QHostAddress::LocalHost, port);  //监听本机上某个端口
    // QHostAddress::LocalHost :IPv4本地主机地址。等价于QHostAddress("127.0.0.1")
    m_pPlainText->appendPlainText("**开始监听...");
    m_pPlainText->appendPlainText("**服务器地址:" + m_pTcpServer->serverAddress().toString());
    m_pPlainText->appendPlainText("**服务器端口:" + QString::number(m_pTcpServer->serverPort()));
    m_pActStartListen->setEnabled(false);  //开始之后不能再开始
    m_pActStopListen->setEnabled(true);
    m_pLabListenStatus->setText(QStringLiteral("监听状态:正在监听"));
}

void MainWindow::slotActStopTriggered() {
    //停止监听
    if (m_pTcpServer->isListening()) {
        m_pTcpServer->close();
        m_pActStartListen->setEnabled(true);
        m_pActStopListen->setEnabled(false);
        m_pLabListenStatus->setText("监听状态:已停止监听");
    }
}

void MainWindow::slotActClearTriggered() { m_pPlainText->clear(); }

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

void MainWindow::slotBtnSendClicked() {
    //发送一行字符串,以换行符结束
    QString msg = m_pLineEdit->text();
    m_pPlainText->appendPlainText("[out]: " + msg);
    m_pLineEdit->clear();
    m_pLineEdit->setFocus();  // 发送完设置焦点

    //字符串的传递一般都要转换为UTF-8格式,编译器不同可能导致乱码,UFTF-8格式是统一的格式,每个编译器都会带,防止乱码
    QByteArray str = msg.toUtf8();  //返回字符串的UTF-8格式
    str.append('\n');
    m_pTcpSocket->write(str);
}

void MainWindow::slotNewConnection() {
    m_pTcpSocket = m_pTcpServer->nextPendingConnection();  //获取socket
    connect(m_pTcpSocket, &QTcpSocket::connected, this, &MainWindow::slotClientConnected);
    // slotClientConnected();
    connect(m_pTcpSocket, &QTcpSocket::disconnected, this, &MainWindow::slotClientDisconnected);
    connect(m_pTcpSocket, &QTcpSocket::stateChanged, this, &MainWindow::slotSocketStateChange);
    slotSocketStateChange(m_pTcpSocket->state());
    connect(m_pTcpSocket, &QTcpSocket::readyRead, this, &MainWindow::slotSocketReadyRead);
}

void MainWindow::slotClientConnected() {
    //客户端接入时
    m_pPlainText->appendPlainText("**client socket connected");
    m_pPlainText->appendPlainText("**peer address: " + m_pTcpSocket->peerAddress().toString());  //对端的地址
    m_pPlainText->appendPlainText("**peer port: " + QString::number(m_pTcpSocket->peerPort()));  //对端的端口
}

void MainWindow::slotClientDisconnected() {
    //客户端断开连接时
    m_pPlainText->appendPlainText("**client socket disconnected");
    m_pTcpSocket->deleteLater();
}

void MainWindow::slotSocketStateChange(QAbstractSocket::SocketState socketState) {
    // socket状态变化时
    switch (socketState) {
        case QAbstractSocket::UnconnectedState: m_pLabSocketState->setText("socket状态:UnconnectedSate"); break;
        case QAbstractSocket::HostLookupState: m_pLabSocketState->setText("socket状态:HostLookupState"); break;
        case QAbstractSocket::ConnectingState: m_pLabSocketState->setText("socket状态:ConnectingState"); break;
        case QAbstractSocket::ConnectedState: m_pLabSocketState->setText("socket状态:ConnectedState"); break;
        case QAbstractSocket::BoundState: m_pLabSocketState->setText("socket状态:BoundState"); break;
        case QAbstractSocket::ClosingState: m_pLabSocketState->setText("socket状态:ClosingState"); break;
        case QAbstractSocket::ListeningState: m_pLabSocketState->setText("socket状态:ListeningState"); break;
    }
}

void MainWindow::slotSocketReadyRead() {
    //读取缓冲区行文本
    while (m_pTcpSocket->canReadLine()) {
        m_pPlainText->appendPlainText("[in]: " + m_pTcpSocket->readLine());
    }
}

QString MainWindow::getLocalIP() {
    //获取本机IPv4地址
    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;
}

4.2 客户端

使用Qt网络模块,需要在配置文件.pro中添加:

Qt += network

MainWindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QAction>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QHostInfo>
#include <QLabel>
#include <QLineEdit>
#include <QMainWindow>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <QPushButton>
#include <QSpinBox>
#include <QTcpSocket>

namespace Ui {
    class MainWindow;
}

class MainWindow : public QMainWindow {
    Q_OBJECT

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

protected:
    void closeEvent(QCloseEvent* event);

private slots:
    //工具栏按钮
    void slotActConnectTriggered();
    void slotActDisConnectTriggered();
    void slotActClearTriggered();
    void slotActQuitTriggered();

    //界面按钮
    void slotBtnSendClicked();

    //自定义槽函数
    void slotConnected();
    void slotDisconnected();
    void slotSocketStateChange(QAbstractSocket::SocketState socketState);
    void slotSocketReadyRead();

private:
    Ui::MainWindow* ui;

    QAction* m_pActConnectServer;
    QAction* m_pActDisconnect;
    QAction* m_pActClear;
    QAction* m_pActQuit;
    QWidget* m_pCentralWidget;
    QLabel* m_pLabel1;
    QLabel* m_pLabel2;
    QLineEdit* m_pLineEditIP;
    QSpinBox* m_pSpinBoxPort;
    QLineEdit* m_pLineEdit;
    QPushButton* m_pBtnSend;
    QPlainTextEdit* m_pPlainText;
    QLabel* m_pLabSocketState;
    QTcpSocket* m_pTcpClient;

    QString getLocalIP();
    void loadStyleFile();
};

#endif  // MAINWINDOW_H

MainWindow.cpp

#include "mainwindow.h"

#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
    ui->setupUi(this);
    this->setWindowTitle(QStringLiteral("TCP客户端"));
    ui->menuBar->hide();

    // QSS样式
    loadStyleFile();

    //工具栏
    ui->mainToolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
    ui->mainToolBar->setMinimumHeight(50);
    m_pActConnectServer = new QAction(QIcon(":/new/prefix1/res/链接.png"), QStringLiteral("连接服务器"), this);
    m_pActDisconnect = new QAction(QIcon(":/new/prefix1/res/断开链接.png"), QStringLiteral("断开连接"), this);
    m_pActClear = new QAction(QIcon(":/new/prefix1/res/清空数据.png"), QStringLiteral("清空文本框"), this);
    m_pActQuit = new QAction(QIcon(":/new/prefix1/res/退出.png"), QStringLiteral("退出"), this);
    ui->mainToolBar->addAction(m_pActConnectServer);
    ui->mainToolBar->addAction(m_pActDisconnect);
    ui->mainToolBar->addAction(m_pActClear);
    ui->mainToolBar->addSeparator();
    ui->mainToolBar->addAction(m_pActQuit);

    //布局
    m_pCentralWidget = new QWidget(this);
    m_pLabel1 = new QLabel(QStringLiteral("服务器地址"), m_pCentralWidget);
    m_pLabel2 = new QLabel(QStringLiteral("端口"), m_pCentralWidget);
    m_pLineEditIP = new QLineEdit(m_pCentralWidget);
    m_pSpinBoxPort = new QSpinBox(m_pCentralWidget);
    m_pSpinBoxPort->setMinimum(1);
    m_pSpinBoxPort->setMaximum(65535);
    QHBoxLayout* HLay1 = new QHBoxLayout();
    HLay1->addWidget(m_pLabel1, 2);
    HLay1->addWidget(m_pLineEditIP, 6);
    HLay1->addWidget(m_pLabel2, 2, Qt::AlignRight);
    HLay1->addWidget(m_pSpinBoxPort, 3);
    m_pLineEdit = new QLineEdit(m_pCentralWidget);
    m_pBtnSend = new QPushButton(QStringLiteral("发送消息"), m_pCentralWidget);
    QHBoxLayout* HLay2 = new QHBoxLayout();
    HLay2->addWidget(m_pLineEdit, 10);
    HLay2->addWidget(m_pBtnSend, 2);
    m_pPlainText = new QPlainTextEdit(m_pCentralWidget);
    QGridLayout* GridLayout = new QGridLayout(m_pCentralWidget);
    GridLayout->addLayout(HLay1, 0, 0);
    GridLayout->addLayout(HLay2, 1, 0);
    GridLayout->addWidget(m_pPlainText);
    this->setCentralWidget(m_pCentralWidget);

    //状态栏
    m_pLabSocketState = new QLabel(this);
    m_pLabSocketState->setText(QStringLiteral("socket状态:"));
    ui->statusBar->addWidget(m_pLabSocketState);
    m_pLabSocketState->setMinimumWidth(150);

    QString localIP = getLocalIP();
    this->setWindowTitle(this->windowTitle() + "---本机IP:" + localIP);
    m_pLineEditIP->setText(localIP);

    m_pTcpClient = new QTcpSocket(this);
    connect(m_pActConnectServer, &QAction::triggered, this, &MainWindow::slotActConnectTriggered);
    connect(m_pActDisconnect, &QAction::triggered, this, &MainWindow::slotActDisConnectTriggered);
    connect(m_pActClear, &QAction::triggered, this, &MainWindow::slotActClearTriggered);
    connect(m_pActQuit, &QAction::triggered, this, &MainWindow::slotActQuitTriggered);
    connect(m_pBtnSend, &QPushButton::clicked, this, &MainWindow::slotBtnSendClicked);
    connect(m_pTcpClient, &QTcpSocket::connected, this, &MainWindow::slotConnected);
    connect(m_pTcpClient, &QTcpSocket::disconnected, this, &MainWindow::slotDisconnected);
    connect(m_pTcpClient, &QTcpSocket::stateChanged, this, &MainWindow::slotSocketStateChange);
    connect(m_pTcpClient, &QTcpSocket::readyRead, this, &MainWindow::slotSocketReadyRead);
}

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

void MainWindow::closeEvent(QCloseEvent* event) {
	//关闭之前断开连接
    if (m_pTcpClient->state() == QAbstractSocket::ConnectedState)
        m_pTcpClient->disconnectFromHost();
    QMessageBox::StandardButton button = QMessageBox::question(this, QStringLiteral(""), "是否退出?");
    if (button == QMessageBox::StandardButton::Yes) {
        event->accept();
    } else {
        event->ignore();
    }
}
void MainWindow::slotActConnectTriggered() {
    //连接到服务器按钮
    QString addr = m_pLineEditIP->text();
    quint16 port = m_pSpinBoxPort->value();
    m_pTcpClient->connectToHost(addr, port);
}

void MainWindow::slotActDisConnectTriggered() {
    //断开连接按钮
    if (m_pTcpClient->state() == QAbstractSocket::ConnectedState) {
        m_pTcpClient->disconnectFromHost();
    }
}

void MainWindow::slotActClearTriggered() { m_pPlainText->clear(); }

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

void MainWindow::slotBtnSendClicked() {
    //发送数据
    QString msg = m_pLineEdit->text();
    m_pPlainText->appendPlainText("[out]: " + msg);
    m_pLineEdit->clear();
    m_pLineEdit->setFocus();
    QByteArray str = msg.toUtf8();
    str.append('\n');
    m_pTcpClient->write(str);
}

void MainWindow::slotConnected() {
    // Connected()信号槽函数
    m_pPlainText->appendPlainText("**已连接到服务器");
    m_pPlainText->appendPlainText("**peer address: " + m_pTcpClient->peerAddress().toString());
    m_pPlainText->appendPlainText("**peer port: " + QString::number(m_pTcpClient->peerPort()));
    m_pActConnectServer->setEnabled(false);
    m_pActDisconnect->setEnabled(true);
}

void MainWindow::slotDisconnected() {
    // Disconnected()信号槽函数
    m_pPlainText->appendPlainText("**已断开与服务器的连接");
    m_pActConnectServer->setEnabled(true);
    m_pActDisconnect->setEnabled(false);
}

void MainWindow::slotSocketStateChange(QAbstractSocket::SocketState socketState) {
    switch (socketState) {
        case QAbstractSocket::UnconnectedState: m_pLabSocketState->setText("socket状态:UnconnectedSate"); break;
        case QAbstractSocket::HostLookupState: m_pLabSocketState->setText("socket状态:HostLookupState"); break;
        case QAbstractSocket::ConnectingState: m_pLabSocketState->setText("socket状态:ConnectingState"); break;
        case QAbstractSocket::ConnectedState: m_pLabSocketState->setText("socket状态:ConnectedState"); break;
        case QAbstractSocket::BoundState: m_pLabSocketState->setText("socket状态:BoundState"); break;
        case QAbstractSocket::ClosingState: m_pLabSocketState->setText("socket状态:ClosingState"); break;
        case QAbstractSocket::ListeningState: m_pLabSocketState->setText("socket状态:ListeningState"); break;
    }
}

void MainWindow::slotSocketReadyRead() {
    while (m_pTcpClient->canReadLine()) {
        m_pPlainText->appendPlainText("[in]: " + m_pTcpClient->readLine());
    }
}

QString MainWindow::getLocalIP() {
    QString hostName = QHostInfo::localHostName();
    QHostInfo hostInfo = QHostInfo::fromName(hostName);
    QString localIP = "";
    QList<QHostAddress> addrList = hostInfo.addresses();
    if (!addrList.isEmpty()) {
        for (int i = 0; i < addrList.size(); i++) {
            QHostAddress aHost = addrList.at(i);
            if (aHost.protocol() == QAbstractSocket::IPv4Protocol) {
                localIP = aHost.toString();
                break;
            }
        }
    }
    return localIP;
}

/* 添加QSS样式 */
void MainWindow::loadStyleFile() {
    QFile file(":/new/prefix1/sytle/style.css");
    file.open(QFile::ReadOnly);
    QString styleSheet = tr(file.readAll());
    this->setStyleSheet(styleSheet);
    file.close();
}

4.3 界面显示

在这里插入图片描述
客户端界面使用了QSS

  • 1
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
05-26
Qt 是一个跨平台应用程序开发框架,其中包括了网络编程模块,可以实现 TCP 协议的网络通信。 在 Qt 中,可以通过 QTcpServerQTcpSocket 类来实现 TCP 服务器和客户端的开发。 QTcpServer 类用于创建 TCP 服务器,可以监听并接受来自客户端的连接请求,并创建一个 QTcpSocket 对象来处理客户端与服务器之间的通信QTcpSocket 类用于创建 TCP 客户端,可以连接到指定的服务器并发送数据,同时可以接收服务器返回的数据。 下面是一个简单的 Qt TCP 服务器的示例代码: ```cpp #include <QTcpServer> #include <QTcpSocket> #include <QDebug> int main(int argc, char *argv[]) { QTcpServer server; if (!server.listen(QHostAddress::Any, 1234)) { qDebug() << "Failed to start server"; return 1; } qDebug() << "Server started"; while (true) { QTcpSocket *socket = server.nextPendingConnection(); if (!socket) continue; qDebug() << "Client connected"; socket->write("Hello, client\n"); socket->flush(); QByteArray data = socket->readAll(); qDebug() << "Received data: " << data; socket->close(); delete socket; } return 0; } ``` 这个示例代码创建了一个 TCP 服务器,并监听所有可用的网络接口的 1234 端口。当有客户端连接时,服务器会发送一条欢迎消息,并等待客户端发送数据。当客户端发送数据后,服务器会将数据打印到控制台,并关闭连接。 类似地,可以编写一个 TCP 客户端来连接到这个服务器并发送数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值