[英]HTTP response connection reset?
I'm writing up a simple web server that implements select components of the http 1.1 protocol and thus far I have a tcp server that serves a static web page to all tcp connections it receives. 我正在编写一个简单的Web服务器来实现http 1.1协议的选择组件,到目前为止,我有一个tcp服务器,它为它接收的所有tcp连接提供静态Web页面。 I feel like there might be a race condition or some other event happening that I'm not aware of. 我觉得可能会出现竞争状况或其他一些我不知道的事件。
Here's the essence of the code in question: 以下是相关代码的本质:
char hello[] =
"HTTP/1.1 200 OK\r\n"
// "Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT\r\n"
// "Content-Length: 131\r\n"
// "Connection: close\r\n"
"\r\n"
"<html>\n"
"<head>\n"
" <title>An Example Page</title>\n"
"</head>\n"
"<body>\n"
" Hello World, this is a very simple HTML document.\n"
"</body>\n"
"</html>\n";
while(true) {
addrlen = sizeof(peer);
sockd2 = ::accept(_sockd, (sockaddr*)&peer, &addrlen);
if (sockd2 == -1) {
perror("Wrong connection");
continue;
}
write(sockd2, hello, sizeof(hello));
// close(sockd2);
}
I'm using Google Chrome to connect to localhost:8080 and as is above, the page loads just fine. 我正在使用谷歌浏览器连接到localhost:8080,如上所述,页面加载正常。
If I uncomment the close
call and Connection: close
line, the page won't load and instead the developer console reads Failed to load resource: net::ERR_CONNECTION_RESET
. 如果我取消注释close
调用和Connection: close
行,则页面将不会加载,而开发人员控制台将显示“ Failed to load resource: net::ERR_CONNECTION_RESET
。
If I do the above but also uncomment one of the other http header lines, it loads. 如果我执行上述操作但也取消注释其他http标题行之一,则会加载。
What's going on? 这是怎么回事?
There is no 'race condition' here. 这里没有“竞争条件”。 This is a network error. 这是一个网络错误。
The problem is that you're not reading the request and not terminating the response correctly. 问题是您没有读取请求而没有正确终止响应。
When the browser writes to a connection that you have already closed, your end issues a TCP RST, which is 'connection reset'. 当浏览器写入您已关闭的连接时,您的结束会发出TCP RST,即“连接重置”。
Read the request. 阅读请求。 And you must either close the socket or send a content-length header. 您必须关闭套接字或发送内容长度标头。
You need to read the HTTP 1.1 RFC. 您需要阅读HTTP 1.1 RFC。 It isn't as trivial as you seem to think. 它并不像你想象的那样微不足道。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.