QT TCP 文件上传下载
时间: 2024-12-27 13:12:33 浏览: 16
### 使用 QT 和 TCP 实现文件上传和下载
为了实现基于QT的TCP文件传输功能,可以扩展基本的TCP服务器和客户端模型,在此基础上加入文件读写操作。下面展示了一个简化版的例子,该例子包含了启动服务器、连接到服务器以及发送/接收文件的主要逻辑。
#### 创建TCP服务器端用于接受文件
服务器部分负责监听来自客户端的连接请求并准备接收数据流中的文件内容:
```cpp
#include <QCoreApplication>
#include <QTcpServer>
#include <QTcpSocket>
#include <QFile>
class FileTransferServer : public QObject {
Q_OBJECT
public:
explicit FileTransferServer(QObject *parent = nullptr);
private slots:
void onNewConnection();
void startReceiving();
private:
QTcpServer* server;
};
void FileTransferServer::onNewConnection() {
QTcpSocket* clientConnection = server->nextPendingConnection();
connect(clientConnection, &QTcpSocket::readyRead, this, &FileTransferServer::startReceiving);
}
void FileTransferServer::startReceiving() {
QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender());
QFile file("received_file");
if (!file.open(QIODevice::WriteOnly)) {
qDebug() << "Cannot open file for writing";
return;
}
QByteArray data = socket->readAll();
file.write(data);
file.close();
}
```
此段代码实现了当有新的客户端尝试建立连接时触发`onNewConnection()`函数,并设置好回调以便于接收到数据后调用`startReceiving()`处理实际的数据保存工作[^1]。
#### 构建TCP客户端以发送文件
对于客户端而言,则需先与指定地址上的服务端建立起有效的套接字链接,之后再将本地选定的目标文件逐块传递给对方:
```cpp
#include <QCoreApplication>
#include <QTcpSocket>
#include <QFile>
int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);
QTcpSocket tcpSocket;
QString hostAddress = "127.0.0.1"; // Replace with your server IP address.
quint16 portNumber = 8080; // Use the same port number as defined by the server.
tcpSocket.connectToHost(hostAddress, portNumber);
if (tcpSocket.waitForConnected(5000)) { // Wait up to five seconds before timing out.
QFile localFile("path_to_your_file");
if (!localFile.open(QIODevice::ReadOnly)){
qDebug()<<"Failed to open file.";
return -1;
}
while(!localFile.atEnd()){
QByteArray block = localFile.read(64*1024); // Read chunks of max size 64KB at once.
tcpSocket.write(block);
tcpSocket.flush(); // Ensure all bytes are sent immediately.
}
localFile.close();
tcpSocket.disconnectFromHost();
qDebug()<<"File transfer completed successfully!";
} else{
qDebug()<<"Error: Could not establish connection.";
}
return a.exec();
}
```
上述C++片段展示了怎样利用QTcpSocket类完成向远程主机传送特定路径下存储的文档的任务;这里假设目标机器上运行着兼容的服务进程等待接收这些信息包[^2]。
阅读全文