C# CR 后必须跟 LF

C# CR must be followed by LF

我自己写了一个非常简单的HTTP服务器,我用C# Windows Form来检索我的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: The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF

这可能是因为 \r\n 你的 Content-Type header 里面有。 charset 应该是 Content-Type header 行的一部分。

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