加入收藏 | 设为首页 |

汕尾-使用QT编写实现 TCP Server上位机应用

海外新闻 时间: 浏览:204 次

[本文属原创,转载请附上原文出处链接。]

本篇首要是完成了TCP服务器端的上位机使用,包含数据收发(字符串及十六进制数据),传输文件的功用,经测试可用。下面首要阐明一下几个根据QT的函数:

//服务器端读取数据函数

void Widget::ServerReadData()
{
QString s;
QString buf;
QByteArray data=clientConnection->readAll();
message = QString(data);
if(message.contains ("clientS汕尾-使用QT编写实现 TCP Server上位机应用top"))
{
clientConnection->close ();
ui->serverSendpushButton->se汕尾-使用QT编写实现 TCP Server上位机应用tEnabled (false);
ui->statuslabel->setText (tr("Client disconnect"));
return;
}
if(this->FromHexEnable)
{
for(int i = 0; i < data.count(); i++)
{
s.sprintf("%02X ", data.at(i));
buf += s;
}
ui->servertextBrowser->append(QString(buf));
}
else
ui->servertextBrowser->append(QString(data));
}

//服务器端发送数据函数

void Widget::ServerSendData ()
{
if(!clientConnection)
return;
if(!(clientConnection = tcpServer->nextPendingConnection ())) //假如没有客户端衔接
{
return;
}
QByteArray data;
if (this->my16Enable)
{
data= QString2Hex(ui->serverMessagelineEdit-汕尾-使用QT编写实现 TCP Server上位机应用>text()); //转换为16进制
}else
data.append(ui->serverMessagelineEdit->text());
if(data.isEmpty ())
{
QMessageBox::warning (this, tr("Warnning"), tr("Please enter the send data"));
return;
}
clientConnection->write(data);
}

//获取IP地址函数

void Widget::GetNetworkIP ()
{
IPlist = QNe汕尾-使用QT编写实现 TCP Server上位机应用tworkInterface::allAddresses ();
foreach(QHostAddress IP, IPlist)
{
if(IP.protocol() == QAbstractSocket::IPv4Protocol)
ui->serverIPcomboBox->addItem (IP.toString ());
}
}

//翻开文件

void Widget::openFile()
{
fileName = QFileDialog::getOpenFileName(this);
if(!fileName.isEmpty())
{
ui->readbin->setEnabled(true);
ui->fileStatusLabel->setText(tr("Open file %1 success").arg(fileName));
}
}

//读取文件特点

void Widget::startTransferfile()
{
localFile = new QFile(fileName);
if(!localFile->open(QFile::ReadWrite))
{
qDebug() << "open file error";
return;
}
totalBytes = localFile->size();//文件总巨细
QString currentFileName = fileName.right(fileName.size()- fileName.lastIndexOf('/')-1);
qDebug() << currentFileName;
ui->fileStatusLabel->setText(tr("Sending..."));
ui->progressBar->setMaximum(totalBytes);
bytesToWrite = totalBytes;
file_send_cnt = 0;
timer->start(10);
}

//发送文件并更新进度条

void Widget::timerUpDate()
{
if(file_send_cnt<=totalBytes)
{
timer->start(1000);
//发送数据,并核算发送完数据后剩下数据的巨细
if(bytesToWrite <= 2048)
bytesToWrite = bytesToWrite - clientConnection->write(localFile->read(bytesToWrite));
else
bytesToWrite 元始天尊= bytesToWrite - clientConnection->write(localFile->read(2048));
//更新发送文件进度条
ui->progressBar->setValue(totalBytes-bytesToWrite);
file_send_cnt += 2048;
}
else
{
ui->fi汕尾-使用QT编写实现 TCP Server上位机应用leStatusLabel->setText(tr("Send OK! "));
localFile->close();
tcpServer->close();
}
}

功用已测试可用,完成作用如下: