Read what the browser sent.
Socket ServerSocket = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);
Serversocket.bind (New IPEndPoint (Ipaddress.any, 8080));//program to listen to 8080 port, if the other program already accounted for this port, the program will throw an exception
Serversocket.listen (10);//Start monitoring 10 users
A dead loop is done to allow multiple requests
while (true)
{
Console.WriteLine ("Waiting for a Request");
Socket socket = serversocket.accept ();//wait for someone to request, return the communication channel of the last socket
Console.WriteLine ("came to request");
String Firstline;
using (NetworkStream stream = new NetworkStream (socket))
using (StreamReader reader = new StreamReader (stream))
{
Firstline = reader. ReadLine ();//Read the first line of the page accessed by the user, read get/1.html http/1.1
String line;
while (line = reader. ReadLine ()) = null)
{
Console.WriteLine (line);
if (line. Length <= 0)
{
break;//encountered a blank line, the request is over, no more waiting
If it does not break, it is stuck in the ReadLine () waiting for the data sent by the browser
}
}
}
string[] STRs = Firstline. Split (');
String url = strs[1];//1.html
Content returned to the browser
using (NetworkStream stream = new NetworkStream (socket))
using (StreamWriter write = new StreamWriter (stream))
{
String filePath = @ "D:\1\" + url;
if (file.exists (FilePath))
{
Write. WriteLine ("http/1.1-ok");
Write. WriteLine ();
String html = File.readalltext (FilePath);
Write. WriteLine (HTML);
}
Else
{
Write. WriteLine ("http/1.1 404 Not FOUND");
Write. WriteLine ();
Write. WriteLine ("not Found");
}
}
Socket. Disconnect (false);//Disconnect Communication
}
Server handles static file requests