我创建了一个带有backlog 1的侦听套接字,并连接了64个套接字。
socket.c中
#define _POSIX_C_SOURCE 199309L
#include <arpa/inet.h>
#include <stdio.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <time.h>
int main() {
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_address = {0};
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(8000);
bind(server_socket, (struct sockaddr*)&server_address, sizeof(server_address));
if (listen(server_socket, 1) == 0) {
printf("Listening\n");
} else {
printf("Failed to listen\n");
return 1;
}
for (int i = 0; i < 64; i++) {
int client_socket = socket(AF_INET, SOCK_STREAM, 0);
struct timespec start;
clock_gettime(CLOCK_MONOTONIC, &start);
if (connect(client_socket, (struct sockaddr*)&server_address, sizeof(server_address)) == 0) {
struct timespec end;
clock_gettime(CLOCK_MONOTONIC, &end);
double elapsed = end.tv_sec - start.tv_sec + (end.tv_nsec - start.tv_nsec) / 1e9;
printf("Connected socket #%d in %.3lfs\n", i, elapsed);
} else {
printf("Failed to connect socket #%d\n", i);
}
}
}
输出:
$ gcc -o socket -std=c99 socket.c
$ ./socket
Listening
Connected socket #0 in 0.000s
Connected socket #1 in 0.000s
Connected socket #2 in 0.000s
Connected socket #3 in 0.000s
Connected socket #4 in 1.000s
Connected socket #5 in 0.000s
Connected socket #6 in 3.004s
Connected socket #7 in 0.000s
Connected socket #8 in 3.004s
Connected socket #9 in 0.000s
Connected socket #10 in 3.004s
Connected socket #11 in 0.000s
Connected socket #12 in 3.004s
Connected socket #13 in 0.000s
Connected socket #14 in 3.004s
Connected socket #15 in 0.000s
Connected socket #16 in 3.004s
Connected socket #17 in 0.000s
...
前四个连接是瞬时的,第五个连接是1秒,然后连接在0到3秒之间振荡,直到所有插座连接并且程序退出。此行为是100%可重复的。
我已经广泛阅读了有关TCP连接,Linux网络文档和other resources的内容。
但我仍然无法解释发生了什么。
为什么连接时间变化如此之大?
系统信息
$ uname -a
Linux paul 3.19.0-51-generic #58~14.04.1-Ubuntu SMP Fri Feb 26 22:02:58 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
(/etc/sysctl.conf
为空。)
答案 0 :(得分:1)
listen的文档解释了这一点,&#34;如果底层协议支持重传,则可以忽略该请求,以便稍后在连接时重新尝试成功&#34;。如果您提高积压,您将看到延迟开始变化的点。
答案 1 :(得分:1)
正如David Schwartz所说,这是由于你的积压。处理SYN请求的TCP代码认为接受队列已满并且还有SYN队列。 见here
1287 /* Accept backlog is full. If we have already queued enough
1288 * of warm entries in syn queue, drop request. It is better than
1289 * clogging syn queue with openreqs with exponentially increasing
1290 * timeout.
1291 */
1292 if (sk_acceptq_is_full(sk) && inet_csk_reqsk_queue_young(sk) > 1) {
1293 NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
1294 goto drop;
1295 }
达到上述条件后,您的SYN数据包将被丢弃。客户端的重传在3秒(初始SYN)之后发生,这被接受
如果将backlog设置为65
,则不会看到连接有任何延迟