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. 在连接服务器之前,应该检查socket是否已经连接过其他服务器,如果是,则应该先断开连接再连接新的服务器。

  2. 在文件读取后应该及时关闭文件流对象file。

  3. 发送数据时建议使用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();
}

}

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?