QT开发中文网

QTcpSocket socket; socket.connectToHost(ui->comboBox_IP->currentText(), 2074); if (!socket.waitForConnected(3000)) { qDebug() edit_path->...

这段代码可以上传文件到服务器,但是存在以下问题:

  1. 没有对连接失败的情况进行处理,建议添加错误处理逻辑。

  2. 缺少文件名变量 file_name 的定义和赋值语句。需要将文件名传递给服务器端以便识别。

  3. 在发送数据包前没有判断文件是否成功读取。如果文件打开失败或读取内容为空,可能会导致程序崩溃或发送空数据包。

  4. 数据包中使用了自定义协议头和协议尾,在实际应用中需要确保这些标识符不会与消息体中的内容冲突或混淆,并且能够被正确解析。

综上所述,修改后的代码如下:

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 对象,并在合适的时机进行了资源释放。

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?