Search code examples
c#httptcpstream

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. What am I doing wrong?


Solution

  • 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. 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();