在这段代码中,可以进行一些细节上的优化:
在连接服务器之前,应该检查socket是否已经连接过其他服务器,如果是,则应该先断开连接再连接新的服务器。
在文件读取后应该及时关闭文件流对象file。
发送数据时建议使用write()函数,并指定要发送的数据长度,而不是将所有数据都直接写入缓冲区。这样可以避免一次性写入太多数据导致缓冲区溢出。
修改后的代码如下:
void upload_program::on_toolBtn_upload_clicked() {
//获得文件名
int index = ui->edit_path->text().lastIndexOf("/");
QString filename = ui->edit_path->text().mid(index + 1);
QFile file(ui->edit_path->text());
if (!file.open(QIODevice::ReadOnly)) {
qDebug() << "Failed to open file";
return;
}
QByteArray file_content = file.readAll();
file.close();
// 创建 QTcpSocket 实例
QTcpSocket* socket = new QTcpSocket(this);
// 检查socket是否已经连接过其他服务器,如果是,则应该先断开连接再连接新的服务器。
if (socket->state() == QAbstractSocket::ConnectedState) {
socket->disconnectFromHost();
}
// 连接服务器
socket->connectToHost("192.168.234.100", 2074);
// 等待连接成功
if (socket->waitForConnected()) {
// 准备发送的数据
QByteArray data;
char protocolId = 0xCD;
int nameLen = filename.length();
int contentLen = file_content.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));
// 使用write()函数,并指定要发送的数据长度
int sent_len = socket->write(file_content);
char terminator = 0xDC;
data.append(terminator);
// 发送数据
socket->flush();
}
}