C HTTP 服务器/连接重置
我正在尝试用 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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,感谢您的帮助,我刚刚在关闭客户端套接字之前添加了此内容,并且不再出现 CONNRESET 错误:
OK, thanks for your help, I've just added this before closing client socket, and no more CONNRESET error :
一旦您
接受
它,您就关闭了套接字。因此,连接在另一端重置。如果您想与 HTTP 客户端对话,则必须解析传入的 HTTP 请求,并使用有效的 HTTP 数据进行回复。 (警告:这不是小事。)
请阅读这篇文章:nweb:例如,一个小型、安全的 Web 服务器(仅限静态页面),它对最小 HTTP 服务器需要完成的工作有一个很好的概述。
You're closing the socket as soon as you
accept
it. So the connection is reset on the other end of it.If you want to talk to an HTTP client, you're going to have to parse the incoming HTTP requests, and reply with valid HTTP data. (Warning: that's not trivial.)
Please read this article: nweb: a tiny, safe Web server (static pages only) for example, it has a good rundown of what needs to be done for a minimal HTTP server.