【发布时间】:2025-12-23 13:45:11
【问题描述】:
我正在编写一个基本的 HTTP 客户端,但遇到了一个问题 - 一些 HTTP 服务器正在强制重置,从而导致“对等连接重置”错误。许多 HTTP 服务器都会优雅地关闭连接,但似乎没有一个服务器能够保持连接处于活动状态。
但是,我确信这是我的客户端,因为使用非常相似的源代码的 HTTP 客户端不会表现出相同的行为:它们与相同服务器的连接要么正常关闭,要么保持活动状态。
是什么导致了这个看似不一致的问题?
相关代码:
/* socket */
if ((context->socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
perror("Failed to create socket");
exit(-1);
}
/* connect */
if (connect(context->socket, &context->tx_addr, sizeof(struct sockaddr)) != 0) {
perror("Couldn't connect to server");
exit(-1);
}
/* create header */
snprintf(context->packet, BUFF_SIZE,
"GET %s HTTP/1.1\r\n" \
"Host: %s\r\n\r\n",
conf->request, conf->host);
/* send header */
if ((sendto(context->socket, context->packet, BUFF_SIZE, 0,
NULL, 0))) != BUFF_SIZE) {
perror("Failed to send");
exit(-1);
}
/* receive response */
do {
if ((received = recvfrom(context->socket, context->packet, BUFF_SIZE, 0, NULL,
NULL)) < 0) {
/* THIS is where RST occurs with some servers */
perror("Failed to receive");
exit(-1)
}
if (received >= 0)
context->packet[received] = '\0';
printf("%s", context->packet);
} while (received > 0);
【问题讨论】: