QT实现TCP通讯代码
时间: 2023-01-11 16:55:36 浏览: 83
好的,下面是在 Qt 中实现 TCP 通讯的一些示例代码:
1. 建立一个简单的 TCP 服务器:
```
#include <QTcpServer>
#include <QTcpSocket>
#include <QDebug>
int main(int argc, char *argv[])
{
QTcpServer server;
if (!server.listen(QHostAddress::Any, 1234)) {
qDebug() << "Failed to start the server";
return -1;
}
qDebug() << "Server is running on port" << server.serverPort();
while (true) {
if (server.waitForNewConnection(-1)) {
QTcpSocket *client = server.nextPendingConnection();
qDebug() << "New client connected:" << client->peerAddress().toString();
while (client->waitForReadyRead(-1)) {
QByteArray data = client->readAll();
qDebug() << "Received data:" << data;
client->write(data);
}
qDebug() << "Client disconnected:" << client->peerAddress().toString();
delete client;
}
}
return 0;
}
```
2. 建立一个简单的 TCP 客户端:
```
#include <QTcpSocket>
#include <QDebug>
int main(int argc, char *argv[])
{
QTcpSocket socket;
socket.connectToHost("127.0.0.1", 1234);
if (!socket.waitForConnected(-1)) {
qDebug() << "Failed to connect to the server";
return -1;
}
qDebug() << "Connected to the server";
socket.write("Hello, server!");
if (!socket.waitForBytesWritten(-1)) {
qDebug() << "Failed to write to the server";
return -1;
}
qDebug() << "Data written to the server";
if (!socket.waitForReadyRead(-1)) {
qDebug() << "Failed to read from the server";
return -1;
}
qDebug() << "Received data:" << socket.readAll();
socket.disconnectFromHost();
if (!socket.waitForDisconnected(-1)) {
qDebug() << "Failed to disconnect from the server";
return -1;
}
qDebug() << "Disconnected from the server";
return 0;
}
```
这些代码是极其简单的示例,仅供参考。在实际应用中,你需要处理更多的细节,如错误处理、断开
阅读全文