#include "transfer_srv.h"
qint64 blockSize = 4*1024;
transfer_srv::transfer_srv(QObject *parent) :
QObject(parent)
{
count = 0;
while (!tcpServer.isListening()
&& !tcpServer.listen(QHostAddress::LocalHost, 9100))
{
qDebug() << "Server cannot listen on port " << 9100;
return;
}
connect(&tcpServer, SIGNAL(newConnection()),
this, SLOT(on_newConnection()));
qDebug() << "start service...";
}
void transfer_srv::on_newConnection ()
{
tcpSocket = tcpServer.nextPendingConnection();
qDebug() << "connection to : " << tcpSocket;
connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(on_readyRead()));
connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(on_error(QAbstractSocket::SocketError)));
connect(tcpSocket, SIGNAL(bytesWritten(qint64)),
this, SLOT(on_bytesWritten(qint64)));
}
void transfer_srv::on_error (QAbstractSocket::SocketError)
{
qDebug() << "on_error() : " << tcpSocket->errorString();
tcpSocket->close ();
count = 0;
}
void transfer_srv::on_readyRead()
{
int type;
QDataStream in (tcpSocket);
in >> type;
if(type == DOWN_GET_FILE) {
QString fileName;
in >> fileName;
qDebug () << "require file : " << fileName;
file = new QFile(fileName);
if (!file->open(QFile::ReadOnly )) {
qDebug () << tr("cannot open file");
return;
}
byteToWrite = file->size();
QByteArray tmp;
tmp = file->read(qMin(blockSize, byteToWrite));
byteToWrite -= qMin(blockSize, byteToWrite);
QByteArray outBlock;
QDataStream out(&outBlock, QIODevice::WriteOnly);
out << DOWN_TRANSFER << tmp;
int num = tcpSocket->write (outBlock);
qDebug () << "count = " << count ++ << "size: " << num ;
}
}
void transfer_srv::on_bytesWritten(qint64 numBytes)
{
static bool status = true;
if(status == false)
return;
QByteArray outBlock;
QDataStream out(&outBlock, QIODevice::WriteOnly);
if(byteToWrite > 0) {
QByteArray tmp;
tmp = file->read(qMin(blockSize, byteToWrite));
byteToWrite -= qMin(blockSize, byteToWrite);
out << DOWN_TRANSFER << tmp;
tcpSocket->write (outBlock);
qDebug () << "count = " << count ++ << "size: " << outBlock.size();
} else {
tcpSocket->flush();
qDebug() << "end" ;
out << DOWN_OVER ;
file->close ();
tcpSocket->write (outBlock);
tcpSocket->flush();
status = false;
}
}
- 1
- 2
- 3
- 4
前往页