Hi everyone. I’m gonna demonstrate how to do proper file uploading and downloading via TCP sockets. I’m going to be using Windows Sockets API (winsock) in this. But the following can be done on linux sockets too.

Why This?

Well, A lot of new socket programmers have a hard time sending and receiving files in C/C++. And I myself had a hard time figuring out. After many really bad implementations. The one I’m going to show you today, Is the one that is so far the best one.

I’m going to skip over basic socket operations such as creating socket, connecting to server and all. Let’s start with a simple receive loop.

The above snippet expects, That the socket socket is connected. And we are receving data in a while loop. If the received data is “Savethisfile”, Then we receive the file. So lets do that now.

I’m also going to skip another step here. Which is sending the file name To save the file into. You can easily do that by sending the file name after, Or sending something like Savethisfile=lol.exe and the client parses it to save the file lol.exe.

Over here, I’ll receive in demo.txt.

This receives the file in chunks, And those chunks are written to the file. This will work on overlapped / non overlapped socket.
Now for the uploading part.

That code is a working prototype for socket file transfer. If you much improve it and tune it to your needs, It will look something like this.

Categories: Uncategorized

Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x