宿題用に非常に基本的な 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);
}
}
プログラムを実行すると、次のようになります。
ご覧のとおり、最初のループはうまく機能します。問題は、同じクライアントではない他のクライアントに接続することを望んで再びループするときに発生します。