[英]C# Simple HTTP Server not sending response to browser
System.Net.Sockets.TcpListener server = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 8080);
server.Start();
Console.WriteLine("Servidor TCP iniciado");
Console.WriteLine("Aguardando conexao de um cliente...");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Um cliente conectou-se ao servidor");
System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream());
writer.Write("HTTP/1.0 200 OK\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\nGoodbye, World!\r\n");
writer.Flush();
Console.WriteLine("Desligando servidor");
server.Stop();
Console.ReadKey();
When I open the browser and try to access the URL http://localhost:8080 I get the ERR_CONNECTION_RESET error. 当我打开浏览器并尝试访问URL http:// localhost:8080时 ,出现ERR_CONNECTION_RESET错误。 What am I doing wrong?
我究竟做错了什么?
The problem is that you have an incorrect HTTP Packet, it does not contain a Content-Length, so the browser does not know what to read. 问题是您的HTTP数据包不正确,它不包含Content-Length,因此浏览器不知道读取什么。 Try the following code:
尝试以下代码:
TcpListener server = new TcpListener(System.Net.IPAddress.Loopback, 8080);
server.Start();
Console.WriteLine("Wait for clients");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Writing content");
string content = "Goodbye World!";
System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream());
writer.Write("HTTP/1.0 200 OK");
writer.Write(Environment.NewLine);
writer.Write("Content-Type: text/plain; charset=UTF-8");
writer.Write(Environment.NewLine);
writer.Write("Content-Length: "+ content.Length);
writer.Write(Environment.NewLine);
writer.Write(Environment.NewLine);
writer.Write(content);
writer.Flush();
Console.WriteLine("Disconnecting");
client.Close();
server.Stop();
Console.ReadKey();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.