Reputation: 36050
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:
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.
Upvotes: 2
Views: 332
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