send/recv 是否以相同的块传输数据?
从我的客户端:
send(socket, "this is a buffer", ...);
send(socket, "second buffer", ...);
从我的服务器,recv
保证以“这是一个缓冲区”
中的r
结束一个块并开始另一个块与来自“第二个缓冲区”
的s
?
From my client:
send(socket, "this is a buffer", ...);
send(socket, "second buffer", ...);
From my server, is recv
guaranteed to end one chunk with the r
from "this is a buffer"
and begin another chunk with the s
from "second buffer'
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,一点也不。由于网络的所有处理,您无法控制收到数据时会发生什么。您不能对在任何 recv 调用中获得多少金额做出任何假设(除非它将 <= 发送的金额)。您最多可以获得一个字节。
No, not at all. You have no control over what happens when you receive the data due to all of the processing of the network. You can't make any assumption about how much you will get in any recv call (except for that it will be <= the amount sent). You could get as little as one byte.
不,Windows 套接字(与其他基于 TCP 的抽象一样)是流式的。您正在寻找一种使用 Windows 套接字的分组方式。
试试这个:
http://tangentsoft.net/wskfaq/examples/packetize.html
No, Windows sockets (like other TCP-based abstractions) are streaming. You are looking for a packetized way to use Windows sockets.
Try this:
http://tangentsoft.net/wskfaq/examples/packetize.html
我不会依赖这一点。阅读时,您可能一下子就明白了。中间有很多事情 - 数据包重新排序、网络延迟等,这些因素都会影响数据包实际到达另一端的时间,并且第二个缓冲区可能会比第一个缓冲区更快地找到路径并会等待(如果您正在使用 TCP,如果没有则不使用)第一个到达。然后无论到达什么都会给你。您应该在接收端解析数据,而不依赖于数据的发送方式(TCP 为您提供一定的顺序保证,UDP 也不这样做)。
I wouldn't rely on that. When reading, you might get them all at once. There are many things in between - packet reordering, network latency, etc, that influence when your packets actually arrive to the other side, and it might be that the second buffer might find its way through faster than the first and will wait (if you're using TCP, or not if not) for the first one to arrive. Then whatever arrived will be given to you. You should parse your data on the receiving side without relying on how it was sent (TCP provides you certain order assurances, UDP doesn't do that either).
如果您希望recv 阻塞直到收到指定数量的字节,您可以使用标志MSG_WAITALL。
http://pubs.opengroup.org/onlinepubs/007904975/functions/recv.html
If you want recv to block until you have received a specified amount of bytes, you can use the flag MSG_WAITALL.
http://pubs.opengroup.org/onlinepubs/007904975/functions/recv.html
对于 UDP 和其他数据报协议,数据包边界将按照您的意愿保留。对于 TCP 和其他流协议来说,就没有这样的运气了。
For UDP and other datagram protocols, packet boundaries will be preserved like you want. For TCP and other stream protocols, no such luck.