在 C++ 中使用套接字进行文件传输
我希望使用 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您可以接受特定于 Winsock 的解决方案,请查看
TransmitFile()
函数。 Linux 和 Solaris 都有一个sendfile()
函数来执行类似的方式,尽管我相信 Linux 和 Solaris 的sendfile()
API 略有不同。这些函数提供了额外的好处,即不必将文件内容复制到地址空间中。否则,有几个选项,包括但不限于以下内容:
sendfile()
和TransmitFile()
函数仍然会更快。与往常一样,分析您的代码。您可能需要考虑的另一件事是您是否希望套接字写入操作是阻塞的还是非阻塞的,在接收端也是如此。非阻塞 IO 将要求您使用平台的事件多路分解机制(例如 POSIX 平台上的
select()
)。Boost.Asio 可能会大大简化您的任务,因为出色地。如果可能的话,我建议在本机 API 上使用它。
哈!
If a Winsock-specific solution is okay with you, take a look at the
TransmitFile()
function. Linux and Solaris both have asendfile()
function that perform in a similar way, although I believe Linux and Solaris have a slightly differentsendfile()
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:
sendfile()
andTransmitFile()
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 (e.g.
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!
将文件转换为字节流,然后通过套接字发送该文件,并在服务器上将其作为字节流读取。
Turn the file to a byte stream, and send this across the socket and read it as a bytestream on the server.
您还可以查看 CSocketFile
根据 MSDN
CSocketFile 类派生自 CFile,但它不支持 CFile 成员函数,例如定位函数(Seek、GetLength、SetLength 等)、锁定函数(LockRange、 UnlockRange)或 GetPosition 函数。 CSocketFile 对象必须做的就是向关联的 CSocket 对象写入字节序列或从关联的 CSocket 对象读取字节序列。
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.