【问题标题】:C# CR must be followed by LFC# CR 后面必须跟 LF
【发布时间】:2015-05-14 02:42:12
【问题描述】:

我自己编写了一个非常简单的 HTTP 服务器,并使用 C# Windows 窗体来检索我的 HTTP 服务器的内容。我的 C# 程序总是说协议违例,CR 后面必须跟 LF。我知道可以通过将配置文件添加到 C# 项目来解决此问题。但我想知道确切的原因。我的 http 服务器代码如下。

/*
 * This will handle connection for each client
 * */
void *httpconnection_handler(void *socket_desc)
{
    //Get the socket descriptor
    int sock = *(int*)socket_desc;
    int read_size;
    char *message = "HTTP/1.1 200 OK\r\nContent-Type: text/xml; \r\ncharset=utf-8\r\n\r\n";
    char *end = "\r\n";
    char send_message[3000] = {0};

    //Send some messages to the client
    char * buffer = 0;
    long length;
    FILE * f = fopen ("/mnt/internal_sd/device-desc.xml", "r");
    if (f)
    {
      fseek (f, 0, SEEK_END);
      length = ftell (f);
      fseek (f, 0, SEEK_SET);
      buffer = malloc (length);
      if (buffer)
      {
        fread (buffer, 1, length, f);
      }
      fclose (f);
    }

    strcat(send_message, message);
    strcat(send_message, buffer);
    strcat(send_message, end);


    write(sock , send_message , length + strlen(message));
    sleep(1);
    shutdown(sock, SHUT_WR);
    //Free the socket pointer
    close(sock);

    return 0;
}

我的 C# 代码在下面。

using (WebClient webClient = new WebClient())
{
    webClient.Encoding = Encoding.UTF8;
    contents = webClient.DownloadString(url);
}

确切的异常消息是

RequestFailed:服务器违反了协议。 Section=ResponseHeader Detail=CR后面必须跟LF

【问题讨论】:

  • 请显示您如何使用 C# 调用它以及确切您收到的错误文本,包括异常类型和它包含的消息,以及任何内部异常(如果有) .

标签: c# c sockets http httpresponse


【解决方案1】:

这可能是因为 \r\n 在您的 Content-Type 标头中。 charset 应该是 Content-Type 标题行的一部分。

char *message = "HTTP/1.1 200 OK\r\nContent-Type: text/xml;charset=utf-8\r\n\r\n";

【讨论】:

  • 另外,如果绝对需要使用多行(在这种情况下不是),您可以将空格移动到正确的位置:char *message = "HTTP/1.1 200 OK\r\nContent-Type: text/xml;\r\n charset=utf-8\r\n\r\n";
  • @SamiKuhmonen - 同意 - 不惜一切代价避免折线。例如,IE 无法正确处理它 - lists.w3.org/Archives/Public/ietf-http-wg/2015AprJun/0215.html
猜你喜欢
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 2011-03-07
  • 1970-01-01
  • 2010-12-04
相关资源
最近更新 更多