将文件的内容发送给客户端
我正在编写一个名为 quote of the day 的 C++ 服务器端应用程序。我正在使用winsock2 库。我想使用 send 函数将文件的内容发送回客户端,包括换行符。我尝试的方法行不通。我该怎么做呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
读取文件和写入套接字是两个不同的操作。 Winsock 没有用于发送直接归档。
至于读取文件,如果使用 fopen,只需确保以读取二进制模式打开它,或者只需使用 CreateFile 和 ReadFile Win32 API,默认为二进制模式。
通常,您将以块的形式读取文件(例如一次 10KB),然后使用 发送 或 WSAS 发送。完成后,您可以关闭套接字。
在接收端,读取套接字上可用的任何内容,直到套接字关闭。当您将数据读入缓冲区时,将读取的数据写入文件。
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.
嗯...我认为Win32 应该有类似于Linux 中的“sendfile”的东西。
如果没有,您仍然可以使用内存映射(但是,不要忘记处理大小大于可用虚拟地址空间的文件)。您可能需要使用阻塞套接字以避免在所有数据被消耗之前返回到应用程序。我认为有一些“重叠”操作来实现异步 IO。
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.
我建议放弃winsock并使用更现代的东西,例如Boost.Asio:
http://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio/tutorial.html
还有一个传输文件的示例:
http://www.boost.org/doc/libs/1_37_0/doc/html /boost_asio/examples.html
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