Sending the contents of a file to a client

I am writing a C++ server side application called quote of the day. I am using the winsock2 library. I want to send the contents of a file back to the client, including newlines by using the send function. The way i tried it doesn't work. How would i go about doing this?

Answers


Reading the file and writing to the socket are 2 distinct operations. Winsock does not have an API for sending a file directly.

As for reading the file, simply make sure you open it in read binary mode if using fopen, or simply use the CreateFile, and ReadFile Win32 API and it will be binary mode by default.

Usually you will read the file in chunks (for example 10KB at a time) and then send each of those chunks over the socket by using send or WSASend. Once you are done, you can close the socket.

On the receiving side, read whatever's available on the socket until the socket is closed. As you read data into a buffer, write the amount read to a file.


Hmm... I think Win32 should have something similar to "sendfile" in Linux. If it doesn't you still can use memory-mapping (but, don't forgot to handle files with size larger than available virtual address space). You probably will need to use blocking sockets to avoid returning to application until all data is consumed. And I think there was something with "overlapped" operation to implement async IO.


I recommend dropping winsock and instead using something more modern such as Boost.Asio:

http://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio/tutorial.html

There is also an example on transmitting a file:

http://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio/examples.html


Need Your Help

Deploy unmanaged dependecy dll within a .NET control

c# .net c++ visual-c++ deployment

i've a c# wincontrol that depends on a bunch of c++ unmanaged dlls.

questions about multicast

linux multicast

We all know that udp is not reliable,by learning unix network programming I add some hdrs about seq and ts to make udp reliable.the idea is simple.when the receiver receives a packet,it must send a...