【问题标题】:C HTTP Server / Connection ResetC HTTP 服务器/连接重置
【发布时间】:2011-05-19 09:07:33
【问题描述】:

我正在尝试在 c 中创建一个小型 http 服务器,但我在使用 httperf 时遇到了 CONNRESET 错误,为什么?

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>

#include <unistd.h>
#include <errno.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <fcntl.h>

#define SOCKERROR -1

#define SD_RECEIVE 0
#define SD_SEND 1
#define SD_BOTH 2

int server;
int client;

...

int main(int argc, char *argv[])
{
    int status;

    int accepted;

    struct addrinfo hint;
    struct addrinfo *info;

    struct sockaddr addr;
    socklen_t addrsize;

    int yes = 1;

    ...

    // client

    addrsize = sizeof addr;

    while (1)
    {
        memset(&accepted, 0, sizeof accepted);
        memset(&addr, 0, sizeof addr);

        accepted = accept(server, &addr, &addrsize);

        if (accepted == SOCKERROR) {
            warn("Accept", errno);
        } else {
            shutdown(accepted, SD_SEND);
            close(accepted);
        }
    }

    // shutdown

    ...

    return EXIT_SUCCESS;
}

【问题讨论】:

  • httperf 将发送数据,您的应用程序将忽略它...我想要么 perf 工具超时/缓冲区已满并且连接已关闭。如果忽略发送到套接字的 IO,最终一方会放弃,操作系统不会永远缓冲它。

标签: c http connection-reset


【解决方案1】:

accept 后,您将立即关闭套接字。所以连接在它的另一端被重置。

如果您想与 HTTP 客户端通信,您将不得不解析传入的 HTTP 请求,并使用有效的 HTTP 数据进行回复。 (警告:这不是小事。)

请阅读这篇文章:例如nweb: a tiny, safe Web server (static pages only),它很好地概述了最小 HTTP 服务器需要做什么。

【讨论】:

  • 我是否只需要读取和发送任何数据以避免连接错误?
  • @Fabien:当然。如果您不读取或写入数据,则客户端最多会挂起什么也不做。
  • @Fabien:如果您希望 httperf 与您的服务器“合作”,您至少需要实现一些 HTTP 对话框。您需要阅读输入并使用有效的 HTTP 响应进行回复。这不是你用“代码的小例子”就能做到的。
【解决方案2】:

好的,感谢您的帮助,我刚刚在关闭客户端套接字之前添加了这个,并且不再出现 CONNRESET 错误:

char readBuffer[128];
char *sendBuffer = "HTTP/1.0 200 OK\r\n"
    "Content-Type: text/html\r\n"
    "Content-Length: 30\r\n\r\n"
    "<html><body>test</body></html>";

do {
    status = recv(accepted, readBuffer, sizeof readBuffer, MSG_DONTWAIT);
} while (status > 0);

send(accepted, sendBuffer, (int) strlen(sendBuffer), 0);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 1970-01-01
    • 2012-05-02
    • 2017-11-26
    • 1970-01-01
    相关资源
    最近更新 更多