qt 使用tcp协议发送文件
时间: 2024-01-08 12:03:47 浏览: 153
可以使用QT的QTcpSocket类来发送文件。具体步骤如下:
1. 创建QTcpSocket对象并连接到服务器:
```c++
QTcpSocket* socket = new QTcpSocket(this);
socket->connectToHost(serverIP, port);
if (!socket->waitForConnected()) {
// 连接失败
return;
}
```
2. 打开文件并读取数据:
```c++
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly)) {
// 文件打开失败
return;
}
QByteArray fileData = file.readAll();
file.close();
```
3. 发送文件数据:
```c++
socket->write(fileData);
```
4. 等待数据发送完成并关闭连接:
```c++
socket->waitForBytesWritten();
socket->close();
```
完整的代码示例:
```c++
QString fileName = "file.txt";
QString serverIP = "127.0.0.1";
int port = 8888;
QTcpSocket* socket = new QTcpSocket(this);
socket->connectToHost(serverIP, port);
if (!socket->waitForConnected()) {
// 连接失败
return;
}
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly)) {
// 文件打开失败
return;
}
QByteArray fileData = file.readAll();
file.close();
socket->write(fileData);
socket->waitForBytesWritten();
socket->close();
```
阅读全文