我有这段代码可以处理一些非常基本的 http 请求。我希望它支持持久连接。如果我通过 firefox 请求某些页面, session /连接将按预期重用。然而,Chrome 会在每次请求/响应后关闭连接,而不管是否包含 Connection: keep-alive header 。
这是有意为之还是我的读/写循环有误?
#include<sys/socket.h>
// some setup code
listen(sockfd, 5);
// accept new connections
while (true) {
int session_sock_fd = accept(sockfd, (struct sockaddr*)&cli_addr, &clilen);
if (newsockfd < 0) {
// error
} else {
// create session
}
// session main loop, each session runs in its own thread
while(true) {
int n = read(session_sock_fd, buffer, buffer_size);
if (n < 0) {
// connection time out or some error
break;
} else if (n == 0) {
break; // client has closed the conneciton
}
// parse the request
// send response
char* resp_data = "HTTP/1.1 200 OK\r\nConnection: keep-alive\r\n"
"Content-Length: xxx\r\nDate: some date\r\n\r\n"
"response_body\r\n";
n = write(session_sock_fd, resp_data, size);
if (n < 0) {
// error, unable to write to socket
break;
}
}
最佳答案
看来我的问题是我在计算内容长度时没有包括最后的“\r\n”。它现在似乎可以正常工作了!
关于Chrome 响应后关闭 TCP 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41076782/