使用Qt框架可以实现TCP服务器和客户端的功能。本教程将通过构建简单的TCP服务器和客户端示例来说明如何使用Qt进行通信。

首先,安装和设置Qt开发环境。推荐使用Qt Creator IDE。确保已安装Qt Network模块,因为它包含用于网络编程的类。

一、创建TCP服务器

  1. 新建一个名为TcpServer的Qt Widgets Application项目。在工程中包含以下文件:
  • main.cpp : 启动应用程序的入口点。
  • tcpserver.h 和 tcpserver.cpp : 实现TcpServer类的文件。
  • mainwindow.h 和 mainwindow.cpp : 实现主窗口界面的文件。
  1. 修改tcpserver.h,引入必要的头文件并定义TcpServer类:
#ifndef TCPSERVER_H
#define TCPSERVER_H

#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QObject>

class TcpServer: public QTcpServer
{
    Q_OBJECT
public:
    explicit TcpServer(QObject *parent = nullptr);
    bool startServer(quint16 port);
signals:
    void receivedData(const QString &data);
private slots:
    void handleNewConnection();
    void processData();
private:
    QTcpSocket *client;
};

#endif // TCPSERVER_H
  1. 在tcpserver.cpp实现TcpServer类:
#include "tcpserver.h"

TcpServer::TcpServer(QObject *parent) : QTcpServer(parent) {
    client = nullptr;
    connect(this, SIGNAL(newConnection()), this, SLOT(handleNewConnection()));
}

bool TcpServer::startServer(quint16 port) {
    return this->listen(QHostAddress::Any, port);
}

void TcpServer::handleNewConnection() {
    if (client) {
        client->close();
        client->deleteLater();
    }
    client = this->nextPendingConnection();
    connect(client, SIGNAL(readyRead()), this, SLOT(processData()));
}

void TcpServer::processData() {
    QString data = QString::fromUtf8(client->readAll());
    emit receivedData(data);
}
  1. 在mainwindow.h文件中添加如下内容:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "tcpserver.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void showReceivedData(const QString &data);

private:
    Ui::MainWindow *ui;
    TcpServer server;
};

#endif // MAINWINDOW_H
  1. 在mainwindow.cpp文件中添加以下内容:
#include "mainwindow.h"
#include "ui_mainwindow.h"

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

    server.startServer(1234); // 指定监听端口号
    connect(&server, SIGNAL(receivedData(QString)), this, SLOT(showReceivedData(QString)));
}

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

void MainWindow::showReceivedData(const QString &data) {
    ui->textEdit->setText(data);
}

二、创建TCP客户端

  1. 新建一个名为TcpClient的Qt Widgets Application项目。在工程中包含以下文件:
  • main.cpp : 启动应用程序的入口点。
  • tcpclient.h 和 tcpclient.cpp : 实现TcpClient类的文件。
  • mainwindow.h 和 mainwindow.cpp : 实现主窗口界面的文件。
  1. 修改tcpclient.h,引入必要的头文件并定义TcpClient类:
#ifndef TCPCLIENT_H
#define TCPCLIENT_H

#include <QObject>
#include <QTcpSocket>

class TcpClient : public QObject
{
    Q_OBJECT
public:
    explicit TcpClient(QObject *parent = nullptr);
    void connectToServer(const QString &address, quint16 port);
    void sendData(const QString &data);
signals:
    void serverResponse(const QString &response);
private slots:
    void onConnected();
    void onReadyRead();
private:
    QTcpSocket socket;
};

#endif // TCPCLIENT_H
  1. 在tcpclient.cpp实现TcpClient类:
#include "tcpclient.h"
#include <QHostAddress>

TcpClient::TcpClient(QObject *parent) : QObject(parent)
{
    connect(&socket, SIGNAL(connected()), this, SLOT(onConnected()));
    connect(&socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
}

void TcpClient::connectToServer(const QString &address, quint16 port) {
    socket.connectToHost(address, port);
}

void TcpClient::sendData(const QString &data) {
    socket.write(data.toUtf8());
}

void TcpClient::onConnected() {
    qDebug() << "Connected!";
}

void TcpClient::onReadyRead() {
    QString response = QString::fromUtf8(socket.readAll());
    emit serverResponse(response);
}
  1. 在mainwindow.h文件中添加如下内容:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "tcpclient.h"
#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_pushButton_send_clicked();

    void showServerResponse(const QString &response);

private:
    Ui::MainWindow *ui;
    TcpClient client;
};

#endif // MAINWINDOW_H
  1. 在mainwindow.cpp文件中添加以下内容:
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    client(this)
{
    ui->setupUi(this);
    client.connectToServer("127.0.0.1", 1234); //连接到指定服务器IP地址和端口号
    connect(&client, SIGNAL(serverResponse(QString)), this, SLOT(showServerResponse(QString)));
}

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

void MainWindow::on_pushButton_send_clicked()
{
    QString data = ui->lineEdit->text();
    client.sendData(data);
}

void MainWindow::showServerResponse(const QString &response) {
    ui->textEdit->setText(response);
}

现在,TCP服务器可以接收来自客户端的文本,客户端也可以收到服务器的响应。这个教程提供了一个简单易懂的范例,您可以通过扩展其功能,来满足您的实际项目需求。

云服务器推荐

蓝易云国内/海外高防云服务器推荐


海外免备案云服务器链接:www.tsyvps.com

蓝易云香港五网CN2 GIA/GT精品网络服务器。拒绝绕路,拒绝不稳定。


百度搜索:蓝易云

蓝易云是一家专注于香港及国内数据中心服务的提供商,提供高质量的服务器租用和云计算服务、包括免备案香港服务器、香港CN2、美国服务器、海外高防服务器、国内高防服务器、香港VPS等。致力于为用户提供稳定,快速的网络连接和优质的客户体验。
最后修改:2023 年 10 月 15 日
如果觉得我的文章对你有用,请随意赞赏