Search code examples
c#httptcpclienttcplistener

WebBrowser: connection refused


I've spent some time for making Http Server and I decided to use TcpListener class (Before that I used HttpListener). The problem is that each browser gives me the message: "Connection refused". It's pretty weird because browser normally gets http header with content (in this case: html page) and 200 code. Futhermore I see my page for roughly 0.5s and then disappear.

        WebServer ws = new WebServer(SendResponse, address);
        Thread thread = new Thread(new ThreadStart(ws.Run));
        thread.Start();

WebServer class:

    public void Run() {
        _listener = new TcpListener(IPAddress.Any, 8080);
        _listener.Start();

        while(isRunning)
        {
            TcpClient client = _listener.AcceptTcpClient();
            Thread thread = new Thread(() => Connection(client));
            thread.Start();
            Thread.Sleep(1);
        }
    }
    public void Connection(TcpClient client)
    {
        NetworkStream stream = client.GetStream();

        string response = "HTTP/1.0 200 OK\r\n"
            + "Content-Type: text/html\r\n"
            + "Connection: close\r\n"
            + "\r\n";

        byte[] bytesResponse = Encoding.ASCII.GetBytes(response);
        byte[] data = Encoding.ASCII.GetBytes("<!doctype html><html><body><h1>test server</h1></body></html>");

        stream.Write(bytesResponse, 0, bytesResponse.Length);
        stream.Write(data, 0, data.Length);
        stream.Dispose();
    }

I guess it's not Firewall fault because another C# server, for example this one: https://www.codeproject.com/Articles/137979/Simple-HTTP-Server-in-C works like a charm. What's wrong?


Solution

  • I found the answer to my problem. The header Content-Length was missing :)