- 在上传之前可以先检查文件是否存在,避免无效的连接和发送操作。
- 可以将IP地址和端口号设为可配置的选项,方便后续更改。
- 可以考虑使用QIODevice::new可以避免一次性读取整个文件内容造成的内存浪费问题。
- 在发送数据之前可以先检查socket连接状态,确保连接已经建立成功。
- 使用QTcpSocket的waitForReadyRead函数来等待服务器响应,从而判断上传是否成功。
优化代码如下:
void upload_program::on_toolBtn_upload_clicked() {
// 获取文件路径
QString filePath = ui->edit_path->text();
if (filePath.isEmpty() || !QFile::exists(filePath)) {
qDebug() << "File not found!";
return;
}
// 获取文件名
QString fileName = QFileInfo(filePath).fileName();
// 创建 QTcpSocket 实例
QTcpSocket* socket = new QTcpSocket(this);
// 连接服务器
socket->connectToHost(m_serverIp, m_serverPort);
// 等待连接成功
if (socket->waitForConnected(3000)) {
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly)) {
qDebug() << "Failed to open file";
socket->close();
return;
}
while (!file.atEnd()) {
QByteArray fileData = file.read(qMin(file.size(), qint64(MAX_PACKET_SIZE)));
// 准备发送的数据
QByteArray data;
char protocolId = 0xCD;
int nameLen = fileName.length();
int contentLen = fileData.length();
data.append(protocolId);
data.append(reinterpret_cast<const char*>(&nameLen), sizeof(nameLen));
data.append(fileName.toUtf8());
data.append(reinterpret_cast<const char*>(&contentLen), sizeof(contentLen));
data.append(fileData);
char terminator = 0xDC;
data.append(terminator);
// 发送数据
socket->write(data);
}
file.close();
if (!socket->waitForBytesWritten()) {
qDebug() << "Failed to send packet";
}
if (socket->waitForReadyRead(3000)) {
QByteArray response = socket->readAll();
// 根据服务器响