1. 概述
Socket编程中,使用send()传送数据时,返回结果受到以下几个因素的影响:• Blocking模式或non-blocking模式
• 发送缓冲区的大小
• 接收窗口大小
本文档介绍通过实验的方式,得出(收发)缓冲区大小对send结果的影响。实验使用C语言。
2 数据发送和接收的过程
如下图所示,程序调用send()发送数据时,数据将首先进入发送缓冲区,等待发送。系统底层socket负责数据的传送,数据通过网络到达接收方的缓冲区。接收方缓冲区内的数据,等待应用程序调用recv()读取。
3 实验一:Blocking模式下
3.1 实验步骤
发送端:blocking模式send()发送8192字节,使用setsockopt设置SO_SNDBUF改变发送缓冲区的大小。接收端:建立连接后进入睡眠。使用setsockopt设置SO_RCVBUF改变接收缓冲区的大小。
3.2 实验得到的数据

3.3实验结论
“已发送字节 + 缓冲区中待发送字节 > 总字节”时,send()能立即返回,否则处于阻塞等待。4 实验二:Non-Blocking模式下
4.1 实验步骤
发送端:non-blocking模式send()发送8192字节,使用setsockopt设置SO_SNDBUF改变发送缓冲区的大小。接收端:建立连接后进入睡眠。使用setsockopt设置SO_RCVBUF改变接收缓冲区的大小。
4.2 实验数据

4.3 实验结论
随着SNDBUF增大,send()返回已发送字节越大。接收窗口大小对结果影响不是线性的。实际已接收的只有窗口大小。5. 实验原代码
5.1 服务器端代码
1 #include <netinet/in.h>2 #include <sys/socket.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <stdint.h>
6 #include <string.h>
7 #include <errno.h>
8
9 int
10 init_server(int type, const struct sockaddr_in *addr)
11 {
12 int fd;
13 int err = 0;
14 int reuse = 1;
15
16 i