自己寫一個簡單的Web服務器,對加深理解Http協議有很好的幫助,下面就看一下一個基於TcpListener的Web服務器:
class Program
{
static void Main(string[] args)
{
IPAddress address = IPAddress.Loopback;
IPEndPoint endPoint = new IPEndPoint(address, 49152);
TcpListener newserver = new TcpListener(endPoint);
newserver.Start();
Console.WriteLine("開始監聽......");
while (true)
{
TcpClient newclient = newserver.AcceptTcpClient();
Console.WriteLine("已經建立連接");
NetworkStream ns = newclient.GetStream();
System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
byte[] request=new byte[4096];
int lehgth = ns.Read(request, 0, 4096);
string requestString = utf8.GetString(request);
Console.WriteLine(requestString);
string statusLine = "HTTP/1.1 200 OK\r\n";
byte[] statusLineBytes = utf8.GetBytes(statusLine);
string responseBody = "<html><head><body><h1>hello world</h1></body></head></html>";
byte[] responseBodyBytes = utf8.GetBytes(responseBody);
//回應頭部分
string responseHeader = string.Format("Content-Type:text/html;charset=UTF-8\r\nContent-Length:{0}\r\n",responseBody.Length);
byte[] responseHeaderBytes = utf8.GetBytes(responseHeader);
ns.Write(statusLineBytes, 0, statusLineBytes.Length);
ns.Write(responseHeaderBytes, 0, responseHeaderBytes.Length);
ns.Write(new byte[] { 13, 10 }, 0, 2);
ns.Write(responseBodyBytes, 0, responseBodyBytes.Length);
newclient.Close();
if (Console.KeyAvailable)
break;
}
newserver.Stop();
}
運行程序,然後打開浏覽器,在浏覽器窗口中輸入服務器的地址:http://localhost:49152,這時就回看到服務器返回的數據。
查看本欄目