2011-05-19 82 views
0

我想在c中制作一个微小的http服务器,但我得到了与httperf的CONNRESET错误,为什么?C HTTP服务器/连接重置

#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; 
} 
+0

的httperf将发送数据,您的应用程序忽略它......我想象perf工具正在超时/缓冲区正在变满,并且连接正在关闭。如果忽略发送到套接字的IO,最终一方会放弃,操作系统不会永久地缓冲它。 – forsvarir 2011-05-19 09:11:49

回答

3

只要你accept它就关闭了插座。所以连接在另一端被重置。

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

例如,请阅读此文章:nweb: a tiny, safe Web server (static pages only)例如,它有一个很好的简要介绍了最小HTTP服务器需要完成的工作。

+0

我是否只需阅读并发送任何数据以避免connreset错误? – Fabien 2011-05-19 09:14:43

+0

那个......那个...... +1 – forsvarir 2011-05-19 09:15:37

+0

@Fabien:当然。如果你不读或写数据,充其量客户将无所事事。 – Mat 2011-05-19 09:17:57

1

OK,感谢您的帮助,我刚刚关闭客户端套接字前加入这一点,并没有更多的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); 
相关问题