请使用QT建立TCP通信的服务端程序和客户端程序
时间: 2024-12-02 15:22:36 浏览: 10
在Qt中,可以利用其强大的跨平台网络编程库QTcpServer和QTcpClient来创建TCP通信服务端和客户端程序。这里是一个简单的步骤指南:
**服务端程序(server.cpp):**
```cpp
#include <QObject>
#include <QTcpServer>
class Server : public QObject
{
Q_OBJECT
public:
explicit Server(QObject *parent = nullptr)
: QObject(parent), server(new QTcpServer(this))
{
if (server->listen(QHostAddress::Any, 8000)) { // 默认端口8000
emit started();
qInfo() << "Server is listening on port 8000.";
} else {
qCritical() << "Failed to start the server: " << server->errorString();
}
}
signals:
void started();
public slots:
void incomingConnection(int socketDescriptor)
{
QByteArray clientAddress = server->peerAddress().toString();
qInfo() << "New connection from:" << clientAddress;
QTcpSocket *client = new QTcpSocket(this);
connect(client, &QTcpSocket::disconnected, this, &Server::removeClient);
client->setSocketDescriptor(socketDescriptor);
client->write("Welcome to the TCP server!");
}
private:
QTcpServer *server;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Server server;
QObject::connect(&app, &QApplication::aboutToQuit, &server, &Server::deleteLater);
return app.exec();
}
```
**客户端程序(client.cpp):**
```cpp
#include <QObject>
#include <QTcpSocket>
class Client : public QObject
{
Q_OBJECT
public:
explicit Client(const QString &host, int port, QObject *parent = nullptr)
: QObject(parent), socket(new QTcpSocket(this))
{
connect(socket, &QTcpSocket::readyRead, this, &Client::handleData);
if (!socket->connectToHost(host, port)) {
qCritical() << "Failed to connect to server: " << socket->errorString();
return;
}
emit connected();
}
signals:
void connected();
public slots:
void sendData()
{
QByteArray message = "Hello, Server!";
socket->write(message);
}
private slots:
void handleData()
{
QByteArray data = socket->readAll();
qDebug() << "Received from server: " << data.data();
}
private:
QTcpSocket *socket;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Client client(QStringLiteral("localhost"), 8000); // 使用本地主机名和默认端口
QObject::connect(&app, &QApplication::aboutToQuit, &client, &Client::deleteLater);
client.sendData(); // 发送数据
return app.exec();
}
```
阅读全文