写一个小的http服务器,我必须处理“ Connection:keep-alive”标头。在此之前,我使用标准的请求处理模型:为一个请求打开一个连接,然后处理,发送响应,然后关闭连接。但是,“保持活动”可让您重新使用连接。问题是,我该怎么办?我应该使用哪种算法?
我试图这样做:使用accept打开连接->使用recv从客户端套接字读取数据->处理请求->使用send发送响应。该循环一直持续到recv返回值= 0,并在退出循环时关闭连接。但是问题在于,在循环的第二次迭代中,在处理了第一个请求之后,recv被阻止了。请告诉我我错了什么步骤。
for(;;)
{
client *current = client::listen_port(cone.get_socket());//called here to accept
httpHandler worker(current);//this class handles requests, we pass a pointer to the class object in it, which contains information about the client
for(;;)
{
httpParser* temp = new httpParser(current->get_client());// recv is called and the httpParser class parses the request
if (temp->get_recvByte() > 0)
worker.handle(temp);//if recv returned something, we process the request and respond to it
if (temp->get_recvByte() == 0)
break;
if (temp->get_recvByte())
std::cout << "error";
delete temp;
}
}
此构造方法形成标题
heading::heading(const int content_size, const std::string &file)
{
head = "HTTP/1.1 200 OK\r\n";
std::string Content_Type, Content_Length;
std::string extension = file.substr(file.find(".") + 1);
if (extension == "png" || extension == "gif")
Content_Type = "Content-Type: image/apng\r\n";
else if(extension == "jpg")
Content_Type = "Content-Type: image/jpeg\r\n";
else
Content_Type = "Content-Type: text/html\r\n";
head = head + "Server: Cone /r/n" + Content_Type + "Connection: keep-alive\n\n";
}
您有:
"Connection: keep-alive\n\n";
应该是:
"Connection: keep-alive\r\n";
类似地,用正斜杠看起来也不正确
"Server: Cone /r/n"
应该是:
"Server: Cone\r\n"