The simplest Web server

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.