QT是一个跨平台的C++应用程序开发框架,它提供了一套完整的工具和库,用于开发各种类型的应用程序,包括图形用户界面(GUI)应用程序、命令行工具、网络应用程序等。QT提供了丰富的功能和类来简化网络通信的开发,其中包括TCP通信。
TCP通信是一种可靠的、面向连接的通信协议,它在网络中广泛应用于数据传输。与UDP相比,TCP提供了更高的可靠性,但通信时延较大。TCP通信的优点包括数据可靠性、数据顺序保证等,缺点包括通信时延较大、通信开销较大等。
以下是两台电脑通过TCP通信的简单示例代码:
Server端代码:
#include <QTcpServer>
#include <QTcpSocket>
#include <QDebug>int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);QTcpServer server;if (!server.listen(QHostAddress::Any, 1234)) {qDebug() << "Server could not start!";return 1;}qDebug() << "Server started. Waiting for incoming connections...";while (server.isListening()) {QTcpSocket *clientSocket = server.nextPendingConnection();qDebug() << "Client connected.";QObject::connect(clientSocket, &QTcpSocket::readyRead, [&]() {QByteArray data = clientSocket->readAll();qDebug() << "Received data from client:" << data;});QObject::connect(clientSocket, &QTcpSocket::disconnected, [&]() {qDebug() << "Client disconnected.";});}return a.exec();
}
Client端代码:
#include <QTcpSocket>
#include <QDebug>int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);QTcpSocket clientSocket;clientSocket.connectToHost("server_ip_address", 1234);if (!clientSocket.waitForConnected()) {qDebug() << "Failed to connect to server.";return 1;}qDebug() << "Connected to server.";// Send data to serverclientSocket.write("Hello from client!");// Wait for response from serverif (clientSocket.waitForReadyRead()) {QByteArray responseData = clientSocket.readAll();qDebug() << "Received response from server:" << responseData;}// Disconnect from serverclientSocket.disconnectFromHost();return a.exec();
}
在这个示例中,Server端监听1234端口,等待Client的连接。一旦Client连接上,Server接收来自Client的数据并输出。Client连接到Server的IP地址和端口号,发送数据到Server,并等待来自Server的响应。完成通信后,Client断开连接。