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");
using (NetworkStream stream = new NetworkStream (socket))
using (StreamReader reader = new StreamReader (stream))
{
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
}
}
}
Content returned to the browser
using (NetworkStream stream = new NetworkStream (socket))
using (StreamWriter write = new StreamWriter (stream))
{
Write. WriteLine ("http/1.1-ok");
Write. WriteLine ();
Write. WriteLine ("Welcome to China");
}
Socket. Disconnect (false);//Disconnect Communication
}
Start a C # program, open a browser, enter 127.0.0.1:8080
Execution Result:
Request message header content, press F12 on the browser, refresh the page, click Network to see the following:
Return content:
The simplest Web server