#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QFile>
#define LOCALE_8_BIT(STR) QString::fromLocal8Bit(STR)
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
m_tcpServer(NULL),
m_tcpSocket(NULL),
m_bytesreceived(0),
m_bytestotal(0),
m_bytesfilenamesize(0)
{
ui->setupUi(this);
ui->btnDisconnect->hide();
this->setWindowTitle(LOCALE_8_BIT("服务端"));
m_tcpServer = new QTcpServer(this);
m_tcpServer->listen(QHostAddress::Any,520);
connect(m_tcpServer,SIGNAL(newConnection()),this,SLOT(Solt_newConnection()));
}
MainWindow::~MainWindow()
{
delete ui;
delete m_tcpServer;
}
void MainWindow::Solt_newConnection()
{
ui->btnDisconnect->show();
m_tcpSocket = m_tcpServer->nextPendingConnection();
connect(m_tcpSocket,SIGNAL(disconnected()),this,SLOT(Solt_disconnected()));
connect(m_tcpSocket,SIGNAL(readyRead()),this,SLOT(Slot_readyRead()));
}
void MainWindow::Solt_disconnected()
{
ui->btnDisconnect->hide();
m_tcpSocket = NULL;
}
void MainWindow::Slot_readyRead()
{
if(m_tcpSocket == NULL)
{
return;
}
qint64 readLen = m_tcpSocket->bytesAvailable();
qDebug() << "Slot_readyRead" << readLen;
//发送网络数据如果比较小或者网络好就响应一次readyread就可以了,比较大就会响应很多次这里需要if判断
QDataStream dStream(m_tcpSocket);
if(m_bytesreceived == 0) //还没接受任何数据
{
//如果发送了总大小空间数据 和文件名大小
if(readLen >= sizeof(qint64) * 2)
{
qDebug() << LOCALE_8_BIT("头数据接收完成");
dStream >> m_bytestotal;
dStream >> m_bytesfilenamesize;
m_bytesreceived += sizeof(qint64) * 2;
//一次性全部接受完
qDebug() << m_bytestotal << m_bytesfilenamesize << m_bytesreceived << readLen;
if(readLen + m_bytesreceived >= m_bytestotal)
{
QString fileName;
QByteArray data;
dStream >> fileName;
dStream >> data;
qDebug() << LOCALE_8_BIT("接受完成") << fileName << LOCALE_8_BIT(data);
m_bytesreceived = m_bytestotal = m_bytesfilenamesize;
QFile file(fileName);
if(file.open(QIODevice::WriteOnly))
{
file.write(data);
file.close();
}
}
}
}
else //多次接受
{
qDebug() << "n+1:" << readLen + m_bytesreceived << m_bytestotal;
if(readLen + m_bytesreceived >= m_bytestotal)
{
qDebug() << LOCALE_8_BIT("接受完成n+1");
m_bytesreceived = m_bytestotal = m_bytesfilenamesize;
QString fileName;
QByteArray data;
dStream >> fileName;
dStream >> data;
QFile file(fileName);
if(file.open(QIODevice::WriteOnly))
{
file.write(data);
file.close();
}
}
}
}
void MainWindow::on_btnSend_clicked()
{
}
void MainWindow::on_btnDisconnect_clicked()
{
if(m_tcpSocket == NULL)
{
return;
}
m_tcpSocket->close();
}