'C# - TcpListener - not receiving HTML Request header until refreshing the browser 2 times

Here is my Socket which is waiting for client to connect ( browser )

        Server = new TcpListener(Address, Port);
        Server.Start();

        Console.WriteLine("--- Waiting for the client ----");
        TcpClient client = Server.AcceptTcpClient();
        this.strem = client.GetStream();
        byte[] read = new byte[900];
        this.strem.Read(read, 0, read.Length);
        Console.WriteLine(Encoding.UTF8.GetString(read));

        this.sendResponseOk();

The SendResponseOk Method:

        // html
        string htmlResponse = "<html>";
        htmlResponse += "<head><title>ACC Data</title></head>";
        htmlResponse += "<body><h1>ACC Data</h1></body>";
        htmlResponse += "</html>";

        // response header
        string response = "HTTP/1.1 200 OK\r\n";
        response += "Content-type: text/html; charset=utf-8\r\n";
        response += "Content-Length: " + htmlResponse.Length + "\r\n";
        response += "\r\n";
        response += htmlResponse;

        // send
        byte[] sendData = Encoding.UTF8.GetBytes(response);
        this.strem.Write(sendData, 0, sendData.Length);

Where i'm now:

  • Starting the Server [work]
  • Open the Browser and go to Local Address:Port [Loading]
  • Refresh ( hit Enter ) for second time, and i receive the Header [word]
  • The HTML page loaded [Work]

The Problem is when i access to Address:Port for the first time and keep loading until i refresh again.

What i have done:

  • new Thread.
  • change TcpListener to Socket Object.
  • Used Thread.Sleep(1000) between every steps.

Thank you.

UPDATE:

On the Phone it works from the first time, no need to refresh the page maybe something with catch ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source