阻止客户端在基本Web服务器中连接两次

Ton*_*Nam 2 c# webserver tcp

我需要为家庭作业实现一个非常基本的Web服务器.我这样做的方式如下:

        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);                    
            }                
        }
Run Code Online (Sandbox Code Playgroud)

以下是我运行程序时会发生的情况:

在此输入图像描述

所以你可以看到第一个循环效果很好.当我再次循环希望连接不同的客户端时,问题就来了.


编辑

在此输入图像描述

ste*_*hbu 5

听起来你的问题始于使用浏览器并假设它只发出一个请求.它不会 - 它会做其他事情,比如尝试请求FavIcon.使用WGET或使用HttpWebRequest编写测试客户端,它将为您提供一致的可靠结果.如果那不能得到你想要的结果 - 那就回来吧.