[Interest] How to send an arbitrary file over sockets
Ghobad Zarrinchian
gzarrin.edu at gmail.com
Sat May 30 11:03:00 CEST 2020
Thanks for all responses.
Now, I know that i should separate my file into multiple parts and send
each part separately. I recently experienced sending several messages using
consecutive write commands, like below:
socket.write(data1);
socket.write(data2);
socket.write(data3);
...
However, the receiver only receives the last message (e.g. data3) and other
messages are gone!. I also used 'socket.waitForBytesWritten()' after each
'socket.write()', but it didn't help. For this reason, i decided to send
all data as one message. How can i execute consecutive writes to a socket?
Thanks.
On Sat, May 30, 2020 at 5:19 AM Thiago Macieira <thiago.macieira at intel.com>
wrote:
> On Friday, 29 May 2020 16:29:13 PDT Ghobad Zarrinchian wrote:
> > Dear all,
> > I'm writing a client/server application in which the client can send a
> file
> > to the server. At the client side, my code is something like below:
> >
> > QFile fl(file_name);
> >
> > fl.open(QIODevice::ReadOnly);
> >
> > QByteArray fileBytes = fl.readAll();
> >
> > socket->write(fileBytes);
> >
> > fl.close();
> >
> > And at the server side, the code that receives the file is something like
> > this:
> >
> > QByteArray data = client_socket->readAll();
> > QFile
> fl(file_name);fl.open(QIODevice::WriteOnly);fl.write(data);fl.close();
> >
> > While the code above works well with text files, it does not work for
> > other file types (like JPG and PDF files). What is the problem? How
> > should i modify the code so that it works for all kinds of files?
>
> Most likely you didn't wait for the socket to finish receiving everything
> before you called readAll(). Insert a waitForDisconnected() before that
> readAll() and you should receive just fine.
>
> Alternatively, and probably better, you could write to the file after
> every
> readyRead() is emitted. That eliminates the need to buffer the entire file
> in
> memory on the receiver side, while receiving.
>
> Avoiding the buffering on the sender side is let as an exercise for the
> reader.
>
> --
> Thiago Macieira - thiago.macieira (AT) intel.com
> Software Architect - Intel System Software Products
>
>
>
> _______________________________________________
> Interest mailing list
> Interest at qt-project.org
> https://lists.qt-project.org/listinfo/interest
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20200530/50adfd94/attachment.html>
More information about the Interest
mailing list