Q_OBJECT
public:
_ready = false;
connect(this, SIGNAL(connected()), SLOT(onConnected()));
connect(this, SIGNAL(disconnected()), SLOT(onDisconnected()));
connect(this, SIGNAL(bytesWritten(qint64)), SLOT(onWritten(qint64)));
}
if(!_ready) return false;
_ready = false;
device = file;
sendChunk();
}
signals:
void fileTransfered();
void ready();
private slots:
void onConnected(){
_ready = true;
emit ready();
}
void onWritten(qint64 s){
if(device->atEnd()){
// file sent
_ready = true;
emit fileTransfered();
emit ready();
} else sendChunk();
}
void onDisconnected(){
_ready = false;
}
private:
bool _ready;
void sendChunk(){
QByteArray ba
= device
->read
(64000);
// about 64kB qint64 writ = write(ba); // write data to socket
if(writ<ba.size()){ // not all written
for(int i=writ;i<ba.size(); i++) device->ungetChar(ba[i]); // write back to the file buffer
}
}
};
FileSender *fs = new FileSender(this);
connect(fs, SIGNAL(ready()), this, SLOT(send()));
connect(fs, SIGNAL(fileTransfered()), this, SLOT(finish()));
fs->connectToHost("...", 3456);
//...
// slot send():
file
->open
(QFile::ReadOnly);
disconnect(fs, SIGNAL(ready()), this, SLOT(send()));
fs->sendFile(file);
//...
// slot finish():
file->close();
delete file;
connect(fs, SIGNAL(disconnected()), fs, SLOT(deleteLater())); // so that fs deletes itself
fs->disconnectFromHost();
class FileSender : public QTcpSocket {
Q_OBJECT
public:
FileSender(QObject *parent) : QTcpSocket(parent){
_ready = false;
connect(this, SIGNAL(connected()), SLOT(onConnected()));
connect(this, SIGNAL(disconnected()), SLOT(onDisconnected()));
connect(this, SIGNAL(bytesWritten(qint64)), SLOT(onWritten(qint64)));
}
bool sendFile(QIODevice *file){
if(!_ready) return false;
_ready = false;
device = file;
sendChunk();
}
signals:
void fileTransfered();
void ready();
private slots:
void onConnected(){
_ready = true;
emit ready();
}
void onWritten(qint64 s){
if(device->atEnd()){
// file sent
_ready = true;
emit fileTransfered();
emit ready();
} else sendChunk();
}
void onDisconnected(){
_ready = false;
}
private:
QIODevice *device;
bool _ready;
void sendChunk(){
QByteArray ba = device->read(64000); // about 64kB
qint64 writ = write(ba); // write data to socket
if(writ<ba.size()){ // not all written
for(int i=writ;i<ba.size(); i++) device->ungetChar(ba[i]); // write back to the file buffer
}
}
};
FileSender *fs = new FileSender(this);
connect(fs, SIGNAL(ready()), this, SLOT(send()));
connect(fs, SIGNAL(fileTransfered()), this, SLOT(finish()));
fs->connectToHost("...", 3456);
//...
// slot send():
QFile *file = new QFile("...");
file->open(QFile::ReadOnly);
disconnect(fs, SIGNAL(ready()), this, SLOT(send()));
fs->sendFile(file);
//...
// slot finish():
file->close();
delete file;
connect(fs, SIGNAL(disconnected()), fs, SLOT(deleteLater())); // so that fs deletes itself
fs->disconnectFromHost();
To copy to clipboard, switch view to plain text mode
Bookmarks