sockets - 为什么在此网络服务器示例中需要额外的\r\n?

标签 sockets

因此,我正在阅读一本名为《黑客:剥削的艺术》的书,并且正在研究其Tinyweb Server示例。

该代码段如下所示:

fd = open(resource, O_RDONLY, 0); //Try to open file
printf("\tOpening \'%s\'\t",resource);
if(fd==-1){ //File not found
    printf(" 404 Not found:\n");
    send_string(sockfd, "HTTP/1.0 404 NOT FOUND\r\n");
    send_string(sockfd, "Server: Tiny webserver\r\n\r\n");
    send_string(sockfd, "<html><head><title>404 Not Found</title></head>");
    send_string(sockfd, "<body><h1>URL not found</h1></body></html>\r\n");
} else { //Otherwise, serve up the file 
...

那么,为什么在第二个send_string调用中需要额外的\r\n?没有它(例如您取消了整行注释),浏览器将尝试无限加载。

我还注意到,如果您取消注释前两个send_string调用,则页面加载就很好了。您也可以对此发表评论吗?

最佳答案

HTTP响应的格式为:

  • 响应头
  • 空行
  • 响应正文

  • 您需要使用空行来告诉标题结尾处和正文开始处。

    关于sockets - 为什么在此网络服务器示例中需要额外的\r\n?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23274068/

    相关文章:

    c++ - 过滤来自特定 IP 的 UDP 数据包

    c++ - UDP 服务器套接字缓冲区溢出

    c - 一次成功写入()/读取()后套接字 "Bad file desc."

    sockets - Haskell 中的原始套接字

    node.js - Socket.IO TLS 需要 key /证书

    c - 使用 recv 接收传入的 char 数组

    Delphi:限制 TCP 连接

    android - 一段时间后 Android 服务中未接收到 TCP 套接字

    python - Django和Socket服务器: Can I add socket server instance to “memory” ?

    delphi - Delphi 中的 SSL 套接字