在这段代码中,需要确保正确地关闭 QTcpSocket 实例。可以在数据发送之后调用 QTcpSocket 的 close() 方法来关闭连接。
另外,在建立连接、发送数据和关闭连接的过程中可能会出现错误,因此你应该使用 QTcpSocket 的 error() 信号来检测是否发生了错误,并根据具体情况进行处理。例如,可以将错误信息输出到控制台或者显示给用户以提示他们发生了什么问题。
下面是修改后的代码示例:
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();
// 创建 QTcpSocket 实例
QTcpSocket* socket = new QTcpSocket(this);
// 连接服务器
socket->connectToHost(ui->comboBox_ip->currentText(), ui->comboBox_port->currentText().toInt());
// 等待连接成功
if (socket->waitForConnected(3000)) {
// 准备发送的数据
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));
data.append(file_content);
char terminator = 0xDC;
data.append(terminator);
// 发送数据
socket->write(data);
socket->flush();
} else {
qDebug() << "Failed to connect to server:" << socket->errorString();
}
// 等待发送完成
if (socket->waitForBytesWritten(3000)) {
qDebug() << "Data sent successfully!";
} else {
qDebug() << "Failed to send data:" << socket->errorString();
}
// 关闭连接
socket->close();
}
在这个示例中,我们添加了错误处理和关闭连接的代码。首先,如果连接失败,则会输出错误信息到控制台。其次,在发送数据后,我们使用 waitFor