C#CR后必须跟随LF [英] C# CR must be followed by LF
问题描述
我自己编写了一个非常简单的HTTP服务器,然后使用C#Windows窗体检索HTTP服务器的内容.我的C#程序总是说违反协议,CR后必须加LF.我知道可以通过将配置文件添加到C#项目中来解决此问题.但是我想知道确切的原因.我的http服务器代码在下面.
I write a very simple HTTP server by myself, and I use the C# Windows Form to retrieve the content of my HTTP server. My C# program always said protocol violation, CR must be followed by LF. I know this issue can be solved by adding Configuration Files to C# Projects. But I want to know the exactly reason. My http server code is in below.
/*
* 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
RequestFailed: The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF
推荐答案
可能是因为Content-Type
标头中包含了\r\n
. charset
应该是Content-Type
标头行的一部分.
It may be because of the \r\n
you have inside of your Content-Type
header. The charset
should be part of the Content-Type
header line.
char *message = "HTTP/1.1 200 OK\r\nContent-Type: text/xml;charset=utf-8\r\n\r\n";
这篇关于C#CR后必须跟随LF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!