我无法理解以下代码段的工作方式和原因:
/* 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 个字节
再说一遍,为什么?