一、Tcplistener搭建web server
1、同socket类似,Tcplistener其实是对socket的封装,方便编程,先初始化tcplistener并且开始监听
//初始化端点信息
IPAddress address = IPAddress.Loopback;
IPEndPoint endPoint = new IPEndPoint(address, );
//初始化并启动监听器
TcpListener server = new TcpListener(endPoint);
server.Start();
Console.WriteLine("Start listening...\n");
2、然后在一个循环中加上监听到的Tcpclient进行相应处理。在这里,与socket不同,Tcplistener将监听到的请求返回成NetworkStream对象
方便程序员编程,使用流的方式进行读写即可
while (true)
{
//挂起并接受请求
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Create a connection.");
//获取网络流对象
NetworkStream ns = client.GetStream();
//使用utf8转码
System.Text.Encoding utf8 =System.Text.Encoding.UTF8;
byte[] request = new byte[];
int length = ns.Read(request, , );
string requestString = utf8.GetString(request, , length);
Console.WriteLine(requestString); //初始化状态行
string statusLine = "HTTP/1.1 200 OK\r\n";
byte[] statusLineBytes = utf8.GetBytes(statusLine); //初始化回应的主体
string responseBody = "<html><head><title>From Server</title></head><body><h1>Server Test [TcpListener]</h1></body></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,,statusLineBytes.Length);
ns.Write(responseHeaderBytes, , responseHeaderBytes.Length);
ns.Write(new byte[] { , }, , );
ns.Write(responseBodyBytes, , responseBodyBytes.Length); //关闭TcpClient对象,回收资源
client.Close();
if (Console.KeyAvailable)
break;
}
server.Stop();
3、至此,web server搭建完成
二、基于HttpListener搭建Web Server
1.在.net命名空间System.Net中提供了HttpListener类,该类使用Http.sys系统组件方可工作,故应先检查系统是否支持。初始化HttpListener对象并开始监听
//查看系统是否支持
if (!HttpListener.IsSupported)
throw new System.InvalidOperationException("Your system must be winXP or Server 2003 or later");
string[] prefixes = new string[] { "http://localhost:23333/" }; //初始化HttpListener
HttpListener listener = new HttpListener();
foreach (string str in prefixes)
listener.Prefixes.Add(str); //开启监听
listener.Start();
Console.WriteLine("Start listening...\n");
2.调用GetContext获取上下文对象,并从该对象解析出request及response。通过request的诸如HttpMethod,AcceptTypes,UserLanguages,UserAgent,Headers等属性获取请求信息。通过设置response相关属性配置回发的相关信息。使用标准流对象将回应回发出去
while (true)
{
//阻塞线程知道请求到来
HttpListenerContext context = listener.GetContext();
//获取请求信息
HttpListenerRequest request = context.Request;
Console.WriteLine("{0} {1} HTTP/1.1",request.HttpMethod,request.RawUrl);
Console.WriteLine("Accept:{0}", string.Join(",", request.AcceptTypes));
Console.WriteLine("Accept-Encoding:{0}", request.Headers["Accept-Encoding"]); //获取response对象
HttpListenerResponse response = context.Response;
//初始化回应主体
string responseString = @"<html><head><title>From HttpListener Server</title></head><body><h1>Server Test[HttpListener]</h1></html>";
//初始化回应内容、长度、编码
response.ContentLength64 = System.Text.Encoding.UTF8.GetByteCount(responseString);
response.ContentType = "text/html;charset=UTF-8";
//输出回应内容
System.IO.Stream output = response.OutputStream;
System.IO.StreamWriter writer = new System.IO.StreamWriter(output);
writer.Write(responseString);
//关闭输出流
writer.Close();
if (Console.KeyAvailable)
break;
}
listener.Stop();
3.演示完成