在 Qt 中进行 TCP 通信需要使用 Qt Network 模块。以下是一个示例代码,演示了如何在 Qt 中建立一个 TCP 服务器和一个 TCP 客户端进行通信:

TCP 服务器端:

#include <QtNetwork>

QTcpServer *server;
QTcpSocket *clientConnection;

void Server::startServer()
{
    server = new QTcpServer(this);
    connect(server, SIGNAL(newConnection()), this, SLOT(acceptConnection()));

    if (!server->listen(QHostAddress::Any, 1234)) {
        qDebug() << "Server could not start!";
    } else {
        qDebug() << "Server started!";
    }
}

void Server::acceptConnection()
{
    clientConnection = server->nextPendingConnection();
    connect(clientConnection, SIGNAL(readyRead()), this, SLOT(readData()));
    connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()));
}

void Server::readData()
{
    QByteArray data = clientConnection->readAll();
    qDebug() << "Received data:" << data;
    // 处理接收到的数据
}

TCP 客户端:

#include <QtNetwork>

QTcpSocket *socket;

void Client::connectToServer()
{
    socket = new QTcpSocket(this);
    connect(socket, SIGNAL(connected()), this, SLOT(connectedToServer()));
    connect(socket, SIGNAL(readyRead()), this, SLOT(readData()));
    connect(socket, SIGNAL(disconnected()), socket, SLOT(deleteLater()));

    socket->connectToHost('127.0.0.1', 1234); // 连接到服务器
}

void Client::connectedToServer()
{
    qDebug() << "Connected to server!";
}

void Client::readData()
{
    QByteArray data = socket->readAll();
    qDebug() << "Received data:" << data;
    // 处理接收到的数据
}

void Client::sendData(const QByteArray &data)
{
    socket->write(data); // 发送数据
}

在上面的示例中,服务器使用QTcpServer类来监听连接请求,并使用QTcpSocket类处理连接和数据传输。客户端使用QTcpSocket类来连接到服务器并进行数据传输。

请注意,上述代码只是一个简单的示例,实际应用中可能需要处理更多的错误和异常情况,例如连接失败、数据传输中断等。


原文地址: https://www.cveoy.top/t/topic/lQSL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录