这段代码可以上传文件到服务器,但是存在以下问题:
没有对连接失败的情况进行处理,建议添加错误处理逻辑。
缺少文件名变量 file_name 的定义和赋值语句。需要将文件名传递给服务器端以便识别。
在发送数据包前没有判断文件是否成功读取。如果文件打开失败或读取内容为空,可能会导致程序崩溃或发送空数据包。
数据包中使用了自定义协议头和协议尾,在实际应用中需要确保这些标识符不会与消息体中的内容冲突或混淆,并且能够被正确解析。
综上所述,修改后的代码如下:
QTcpSocket *socket = new QTcpSocket(this);
connect(socket, SIGNAL(connected()), this, SLOT(onConnected()));
connect(socket, SIGNAL(disconnected()), this, SLOT(onDisconnected()));
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onError(QAbstractSocket::SocketError)));
connect(socket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
QString ip_address = ui->comboBox_IP->currentText();
int port_number = 2074;
QFile file(ui->edit_path->text());
QString file_name = file.fileName().split("/").last(); // 获取文件名
if (!file.open(QIODevice::ReadOnly)) {
qDebug() << "Failed to open file";
return;
}
QByteArray content = file.readAll();
file.close();
if (content.isEmpty()) {
qDebug() << "File is empty";
return;
}
QByteArray packet;
packet.append(char(0xCD)); // 协议头
packet.append(file_name.length());
packet.append(file_name);
packet.append(content.length());
packet.append(content);
packet.append(char(0xDC)); // 协议尾
socket->connectToHost(ip_address, port_number);
if (!socket->waitForConnected(3000)) {
qDebug() << "Failed to connect to server";
return;
}
qint64 bytes_written = socket->write(packet);
if (bytes_written != packet.size()) {
qDebug() << "Failed to send data";
return;
}
if (!socket->waitForReadyRead(5000)) {
qDebug() << "Failed to receive response";
return;
}
QByteArray response = socket->readAll();
qDebug() << "Server response:" << response;
delete socket; // 释放资源
其中,onConnected()、onDisconnected()、onError() 和 onReadyRead() 都是自定义的槽函数,用于处理连接成功、断开连接、发生错误以及收到数据等事件。这里使用了指针类型的 QTcpSocket 对象,并在合适的时机进行了资源释放。