我需要为家庭作业实现一个非常基本的 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);
}
}
这是我运行程序时发生的情况:
如您所见,第一个循环效果很好。当我再次循环希望连接不同的其他客户端时,问题就来了。