我写了一个简单的http服务器,我打算与HttpRequest / Response进行交互。服务器获取请求并且解析很好但是当我回写时我得到异常
System.Net.WebException: Der Server hat eine Protokollverletzung ausgeführt. Section=ResponseStatusLine
bei System.Net.HttpWebRequest.GetResponse()
我的服务器代码回写
TcpClient client = ...;
_stream = _client.GetStream();
// make sure "\r\n" is used as line ending, because it may be different on different OS
_output = new StreamWriter(_stream, Encoding.UTF8) { NewLine = "\r\n" };
length = 0;
code = 200;
message = "OK";
_output.WriteLine("HTTP/1.1 " + code + " " + message);
_output.WriteLine("Server: My Server");
_output.WriteLine("ContentLength: " + length);
_output.WriteLine("Connection: " + (_keepAlive ? "Keep-Alive" : "Close"));
_output.WriteLine();
_output.Flush();
客户端代码
var request = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:8080/foo");
request.KeepAlive = false;
request.ServicePoint.Expect100Continue = false;
using (var res = request.GetResponse()) // throws here
{
}
任何想法?
更新:正如Jon提到的第一个bug被删除但仍无法正常工作
备用客户端代码
using (var client = new TcpClient())
{
client.Connect(new IPEndPoint(IPAddress.Loopback, 8080));
using (var stream = client.GetStream())
{
var writer = new StreamWriter(stream);
writer.WriteLine("GET /foo HTTP/1.1");
writer.WriteLine("HOST:127.0.0.1");
writer.WriteLine("Connection:Close");
writer.WriteLine();
writer.Flush();
var response = new StreamReader(stream).ReadToEnd();
foreach (var c in response)
{
if (char.IsControl(c))
Console.Write("'{0}'" , (int)c);
else
Console.Write(c);
}
}
}
返回
HTTP/1.1 200 OK'13''10'Server: My custom Server'13''10'ContentLength: 0'13''10'Connection: Close'13''10''13''10'
答案 0 :(得分:1)
这一点非常可疑:
_output = new StreamWriter(_stream, Encoding.UTF8) { NewLine = "\n\r" };
我认为您的意思是\r\n
而不是\n\r
。