Tono Nam
Tono Nam

Reputation: 36050

Prevent Client from connecting twice in a basic webserver

I need to implement a very basic web server for homework. The way I do it is as follows:

        TcpListener server = new TcpListener(IPAddress.Any, 8181);
        server.Start();

        // when a client connects this is what we will send back
        var HttpHeader = 
              "HTTP/1.1 200 OK\r\n"
            + "Content-Type: text/html\r\n"
            + "Content-Length: [LENGTH]\r\n\r\n";

        var html = "<h1>Hello Wold</h1>";

        // replace [LENGTH]  with the length of html
        HttpHeader = HttpHeader.Replace("[LENGTH]", html.Length.ToString());

        while (true)
        {
            // wait for client to connect
            var client = server.AcceptTcpClient();

            using (var stream = client.GetStream())
            {
                var messageToSend = HttpHeader + html;
                var sendData = System.Text.Encoding.ASCII.GetBytes(messageToSend);
                stream.Write(sendData, 0, sendData.Length);

                Thread.Sleep(2000);                    
            }                
        }

Here is what happens when I run the program:

enter image description here

So as you can see the first loop works great. The problem comes when I loop again hoping to connect other clients not the same one.


Edit

enter image description here

Upvotes: 2

Views: 332

Answers (1)

stephbu
stephbu

Reputation: 5091

It sounds like your problem starts with using a browser and assuming it'll issue exactly one request. It doesn't - it'll do additional things like try to request FavIcon. Use WGET or write a test client using HttpWebRequest it'll give you consistent reliable results. If that doesn't give the result you want - then come back.

Upvotes: 5

Related Questions