ubuntu+qt demo
功能:1.TCP服务器,接收多客户端
2.接收客户端发来的文件(文本文件,其它多媒体文件(比如各视频文件))
3.显示进度
对于大文件,长连接,会自定义一些协议,实现分包发送,心跳检测,断点续传之类的功能。本文不涉及业务,仅为最小原型,可在此基础上扩展。
关键点:1.发送包头为:名字+长度 eg:filename#totalsize#
2.如果传输的是文本: bool ret=pf->open(QIODevice::WriteOnly|QIODevice::Text);
如果传输的是非文本:bool ret=pf_->open(QIODevice::WriteOnly|QIODevice::Unbuffered);
void mytcpserverfile::doProcessDataReady()
{
QString msg;
QTcpSocket* ptcpsocket = dynamic_cast<QTcpSocket*>(sender());
QString info=ptcpsocket->peerAddress().toString()+":"+QString("%1").arg(ptcpsocket->peerPort());
/* QString strData=QString::fromLocal8Bit(ptcpsocket->readAll())+"\r\n";
msg=QString("读取客户端[%1] 数据:%2").arg(info).arg(strData);
ui->smsg_edittext->append(msg);*/
QByteArray ba=ptcpsocket->readAll();
//frist recv
if(this->recvtotal_==0)
{
this->alltotal_=0;
//eg:filename#totalsize#
QStringList list=QString(ba).split("#");
QString filename=list.at(0);
this->alltotal_=QString(list.at(1)).toLong();
this->alltotal_+=ba.length();
this->recvtotal_+=ba.length();
// qDebug()<< "rec filename="<<filename<<"file size"<<this->alltotal_;
QString saveFilename="/home/tangcj/C++/QTProject/mytcpserverfile/savefiles/"+filename;
pf_->setFileName(saveFilename);
bool ret=pf_->open(QIODevice::WriteOnly|QIODevice::Unbuffered);
if(!ret)
{
QMessageBox::warning(this,"warning","open failed!");
return;
}
msg=QString("服务器 receving...:%1").arg(filename);
ui->smsg_edittext->append(msg);
ui->progressBar->setRange(0,alltotal_);
}
else
{
qint64 len=pf_->write(ba);
this->recvtotal_+=len;
}
//更新进度条
ui->progressBar->setValue(this->recvtotal_);
//是否接收完毕
if(this->recvtotal_==this->alltotal_)
{
pf_->close();
this->recvtotal_=0;
this->alltotal_=0;
msg="文件接收完毕";
ui->smsg_edittext->append(msg);
}
}