qt tcp socket传输数据代码实例
时间: 2024-09-12 20:14:29 浏览: 31
在Qt框架中,可以使用QTcpSocket类来创建TCP套接字并进行数据传输。以下是一个简单的例子,展示了如何创建一个客户端和服务器,并通过TCP连接交换数据:
```cpp
// 客户端(QTcpSocket)示例
#include <QObject>
#include <QTcpSocket>
class Client : public QObject
{
Q_OBJECT
public slots:
void connectToServer() {
QTcpSocket *socket = new QTcpSocket(this);
if (!socket->connectToHost("localhost", 8000)) { // 连接到本地服务器(假设默认IP)
qWarning("Failed to connect: %s", socket->errorString());
return;
}
QByteArray data = "Hello from client"; // 发送的数据
if (socket->write(data) != data.size()) {
qWarning("Failed to write data");
} else {
qDebug("Data sent successfully");
}
// 接收服务器响应
QByteArray reply;
while (socket->bytesAvailable()) {
reply.append(socket->readAll());
}
qDebug("Received: %s", reply.data());
}
private:
~Client() {}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Client client;
client.connectToServer();
return app.exec();
}
// 服务器(QTcpServer)示例
#include <QCoreApplication>
#include <QTcpServer>
class Server : public QTcpServer
{
Q_OBJECT
public:
Server() : QTcpServer(this) {}
public slots:
void incomingConnection(qintptr handle) {
QTcpSocket *socket = new QTcpSocket(this);
if (!accept(socket)) {
qWarning("Failed to accept connection");
return;
}
QByteArray request = socket->readAll(); // 接收客户端发送的数据
emit newConnection(socket, request); // 管理接收请求
socket->write("ACK received"); // 回应客户端
delete socket;
}
signals:
void newConnection(QTcpSocket *client, QByteArray data);
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Server server;
if (!server.listen(QHostAddress::Any, 8000)) {
qCritical("Listen failed: %s", server.errorString());
return -1;
}
qDebug("Server started on port 8000");
return a.exec();
}
```
阅读全文