PDA

View Full Version : sending a file(txt,docs,exe,rar,zip...) through QTcpSocket



toufic.dbouk
29th December 2012, 11:28
Hello friends,
Im really knew to this forum,
i have been trying to write a Qt c++ code for transferring files from client to server over a QTcpServer
i have done some long work and different functions for the whole program including the GUI
but now i wanna implement the download button, where the client has a list of the server files , upon double clicking the client will
download the file from server to his PC.
i tried several ways but non is working out for me
i know i should read the file into chunks and feed the socket the chunk while looping till there is no bytes available
can anyone help
give me a sample code of this or another way or any clue
Thanks in advance.

anda_skoa
29th December 2012, 11:50
Both QFile and QTcpSocket are subclasses of QIODevice, so transferring bytes from the file to the socket is only a matter of finding matching read and write functions.

For example there is QIODevice::read( qint64 ) which returns a block of data as a QByteArray. The matching write function is QIODevice::write( QByteArray ) which takes such a data block and writes it.

Now one thing to consider of course is that the socket needs to transfer data to an "endpoint" that can be considerably slower than a file.
In a situation with blocking I/O one could call QIODevice::waitForBytesWritten() after each write, making sure the data has been sent before calling read() on the file again.
In a situation with non-blocking I/O one would connect to the QIODevice::bytesWritten( int ) signal and only attempt another read/write cycle when all or most data from the previous write has been sent.

Cheers,
_

toufic.dbouk
29th December 2012, 15:01
Thanks for your reply Admin anda_skoa.
im not really familiar with QIODevice, may you please show me a sample code that is supposed to send a file of any type to a server ?
That would be really helpful and ill take a look at the qt reference documentation of QIODevice class to well understand it
Thanks again,

amleto
29th December 2012, 18:03
there are plenty of network examples on the the digia help site.