我希望通过 Windows 套接字发送 API 发送大于 1 MB 的大消息。有没有一种有效的方法可以做到这一点,我不想循环然后分块发送数据。我在某处读到您可以增加套接字缓冲区大小,这可能会有所帮助。谁能详细说明一下。感谢任何帮助
请您参考如下方法:
你应该,事实上必须循环以分块发送数据。
如 Beej 的网络指南中所述:
"send() returns the number of bytes actually sent out—this might be less than the number you told it to send! See, sometimes you tell it to send a whole gob of data and it just can't handle it. It'll fire off as much of the data as it can, and trust you to send the rest later."
这意味着即使您将数据包大小设置为 1MB,send() 函数也可能不会发送所有数据包,您将被迫循环直到调用 send() 发送的总字节数达到您尝试发送的字节数。事实上,数据包的大小越大,send() 发送不完的可能性就越大。
除此之外,您不想发送 1MB 的数据包,因为如果它们丢失,您将不得不再次传输整个 1MB 的数据包,而如果您丢失了一个 1K 的数据包,重新传输它并不是什么大问题。
总而言之,您将不得不循环调用您的 send() ,而接收方甚至也必须循环调用它们的 recv() 。您可能需要在每个数据包前添加一个小 header ,以告知接收方正在发送多少字节,以便接收方可以循环适当的次数。
我建议您查看 Beej 的网络指南,了解有关 send() 和 recv() 的更多详细信息以及如何处理此问题。它可以在 http://beej.us/guide/bgnet/output/print/bgnet_USLetter.pdf 找到