0

I'm trying to make a tiny http server in c but I got CONNRESET errors with httperf, why ?

#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;
}
4

2 回答 2

3

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

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

请阅读这篇文章:nweb:例如,一个小型、安全的 Web 服务器(仅限静态页面),它很好地概述了最小 HTTP 服务器需要做什么。

于 2011-05-19T09:12:16.703 回答
1

好的,感谢您的帮助,我刚刚在关闭客户端套接字之前添加了这个,并且不再出现 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);
于 2011-05-19T09:32:01.510 回答