我无法理解以下代码片段如何以及为什么能够工作:
/* Now lets try to set the send buffer size to 5000 bytes */
size = 5000;
err = setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &size, sizeof(int));
if (err != 0) {
printf("Unable to set send buffer size, continuing with default size\n");
}
如果我们检查发送缓冲区的值,它确实正确设置为5000 * 2 = 10000。 然而,如果我们尝试发送超过发送缓冲区大小的数据,它会将所有数据都发送出去。例如:
n = send(sockfd, buf, 30000, 0);
/* Lets check how much us actually sent */
printf("No. of bytes sent is %d\n", n);
这将打印出30000。
这是怎么做到的呢?发送缓冲区大小限制为10000没有任何影响吗?如果有,会发生什么?一些分段吗?
更新:如果套接字处于非阻塞模式会发生什么?我尝试了以下操作:
- 将缓冲区大小更改为10000(5000 * 2)会导致发送16384字节
- 将缓冲区大小更改为20000(10000 * 2)会导致发送30000字节
再次问一遍,为什么?