QT使用TCP传输文件
server端
-
导入头文件使用指针创建QTcpServer对象和QTcpSocket对象
QTcpServer * tcpServer;
QtcpSocker * tcpSocket
-
给QTcpserver分配对象并对象指定父对象
tcpServer = new QTcpServer(this);
-
打开监听绑定端口
tcpServer->listen(QHostAddress::Any,8888);
-
connect绑定newConnection事件
connect(tcpServer,&QTcpServer::NewConnection,
[=](){
tcpSocket = tcpServer->netPendingConnection();
QString ip = tcpSocket->peerAddress().toString();
qint16 port = tcpSocket->peerPort();
QString str = QString("[%1:%2] 成功连接").arg(ip).arg(port);
ui->textEdit->setText(str);
//成功连接后才能选择文件
ui->pushButton_select->setEnabled(true);
});
-
鼠标点击选择文件事件处理
void Widget::on_pushButton_select_clicked() { // 打开文件,选择文件路径 QString filePath = QFileDialog::getOpenFileName(this,"open","../"); if(false == filePath.isEmpty()){ // 判断是否为空,并初始化文件信息 fileName.clear(); fileSize = 0; sendSize = 0; QFileInfo info = QFileInfo(filePath); fileName = info.fileName(); fileSize = info.size(); ui->progressBar->setMaximum(fileSize); ui->progressBar->setValue(0); file.setFileName(filePath); // 绑定文件名 bool isOK = file.open(QIODevice::ReadOnly); // 只读打开 if(true == isOK) { qDebug() << "打开文件成功"; ui->textEdit->append("成功选择文件"); ui->textEdit->append(QString("文件名:%1文件大小%2KB").arg(fileName).arg(fileSize)); ui->pushButton_send->setEnabled(true); ui->pushButton_select->setEnabled(false); }else{ qDebug() << "打开文件出错"; } } }
-
鼠标点击发送事件处理:发送文件头
void Widget::on_pushButton_send_clicked() { // 新建文件头 QString head = QString("%1##%2").arg(fileName).arg(fileSize); qint64 len = tcpSocket->write(head.toUtf8()); if(len>0) { // 文件头成功发送 // 发送文件内容 // 开启定时器 -- 等待文件头发送20毫秒后发送文件体,防止文件发送时,和文件头混合 timer.start(20); }else{ // 发送失败 qDebug() << "头部发送失败"; ui->textEdit("文件发送失败,请重新选择文件"); file.close(); ui->pushButton_select->setEnabled(true); ui->pushButton_send->setEnabled(false); } }
-
处理QTimer::timeout事件
connect(&timer,&QTimer::timeout, [=](){ timer.stop(); sendData(); });
-
定义sendData()函数
void Widget::sendData(){
qint64 len = 0;// 定义发送长度
do{
// 每次发送数据的大小
char buff[4*1024] = {0};
len = file.read(buff,sizeof(len));
len = tcpSocket->write(buff,len);
sendSize += len;
ui->progressBar->setValue(sendSize);
}while(len>0);
// 判断是否发送完
if(sendSize == fileSize){
qDebug() << "文件发送完成";
ui->textEdit->append("文件发送完毕");
ui->pushButton_select->setEnabled(true);
ui->pushButton_send->setEnabled(false);
}
}