简体   繁体   中英

File transfer using Sockets in C++

I wish to make a file transfer using sockets from client to server using C++ language...

The code I have only transfers strings to client and server.

How can I transfer files? Any help or reference materials would also help.

将文件转换为字节流,然后通过套接字发送该文件,并在服务器上将其作为字节流读取。

If a Winsock-specific solution is okay with you, take a look at the TransmitFile() function. Linux and Solaris both have a sendfile() function that perform in a similar way, although I believe Linux and Solaris have a slightly different sendfile() API. These functions provide the added benefit of not having to copy contents of the file into your address space.

Otherwise there are several options including but not limited to the following:

  • Read chunks of the file into a buffer, and send that buffer over your socket. Keep iterating over the file until the send is complete. Note that you'll have to pay attention to the amount of bytes sent (ie the write operation's return value) to make sure you don't have holes in your data.
  • Memory map the file into your process address space, and write to the socket directly from the memory mapped buffer. This approach saves you from having to copy the content of your file into your process, so it could provide a performance gain when sending a large file. The sendfile() and TransmitFile() functions would still be faster, however. As always, profile your code.

Another thing you might want to think about is whether or not you want the socket write operation to be blocking or non-blocking, and similarly on the receiving end. Non-blocking IO will require you to use your platform's event demultiplexing mechanism (eg select() on POSIX platforms).

Boost.Asio would likely greatly simplify your task, as well. I'd recommend using it over the native APIs if at all possible.

HTH!

You can also look at CSocketFile As per MSDN

Class CSocketFile derives from CFile, but it does not support CFile member functions such as the positioning functions (Seek, GetLength, SetLength, and so on), the locking functions (LockRange, UnlockRange), or the GetPosition function. All the CSocketFile object must do is write or read sequences of bytes to or from the associated CSocket object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM