QT开发中文网

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());

  1. 在上传之前可以先检查文件是否存在,避免无效的连接和发送操作。
  2. 可以将IP地址和端口号设为可配置的选项,方便后续更改。
  3. 可以考虑使用QIODevice::new可以避免一次性读取整个文件内容造成的内存浪费问题。
  4. 在发送数据之前可以先检查socket连接状态,确保连接已经建立成功。
  5. 使用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();
        // 根据服务器响

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://qt.0voice.com/?id=1922

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?