【问题标题】:Chrome closes TCP connection after responseChrome 响应后关闭 TCP 连接
【发布时间】:2017-04-25 21:33:16
【问题描述】:

我有这段代码可以处理一些非常基本的 http 请求。我希望它支持持久连接。如果我通过 firefox 请求某些页面,则会话/连接将作为 indended 重用。然而,Chrome 会在每次请求/响应后关闭连接,与是否包含 Connection: keep-alive 标头无关。

这是有意的还是我的读/写循环错误?

#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;
  }
}

【问题讨论】:

  • 您的内容长度是在您的resp_data 中包含最后的\r\n 还是仅包含response_body
  • @SteffenUllrich 不,它没有,我改变了它。它现在似乎按预期工作。谢谢!

标签: c google-chrome http firefox tcp


【解决方案1】:

看来我的问题是我在计算内容长度时没有包括最后的“\r\n”。它现在似乎可以工作了!

【讨论】:

    猜你喜欢
    • 2018-12-12
    • 2022-01-20
    • 2018-07-02
    • 2013-09-04
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    相关资源
    最近更新 更多