Chrome 响应后关闭 TCP 连接

标签 c google-chrome http firefox tcp

我有这段代码可以处理一些非常基本的 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/

相关文章:

http - 如何在不解析正文的情况下只获取状态码?

web-services - Web 服务中的 REST 无状态和用户 session

c - 如何从 4 个字符的数组中获取一个 int?我不明白给我的答案

c - 在 ANSI C 中不引入额外变量的情况下根据原始值测试赋值结果

c++ - 撤消打印到命令行的换行符 (\n)

Jquery 模态对话框弹出 - 在所有浏览器中固定在屏幕中央

html - Chrome 自动将电子邮件输入用户名登录字段

javascript - mouseup 在 Windows 7 上的 Chrome 中无法触发

javascript - 无法找到解决方案 : JSON. 解析:第 1 行第 1 列数据意外结束

C 指针挫折 EXC_BAD_ACCESS