C#实现HTTP服务器

来源:互联网 发布:python 关闭tcp连接 编辑:程序博客网 时间:2024/06/05 16:37

.net框架下有一个简单但很强大的类HttpListener。这个类几行代码就能完成一个简单的服务器功能。虽然以下内容在实际运行中几乎毫无价值,但是也不失为理解HTTP请求过程的细节原理的好途径。

<pre name="code" class="html">HttpListener httpListener = new HttpListener();                       httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;                httpListener.Prefixes.Add("http://localhost:8080/");                httpListener.Start();               new Thread(new ThreadStart(delegate                {                    while (true)                    {                                                     HttpListenerContext httpListenerContext = httpListener.GetContext();                            httpListenerContext.Response.StatusCode = 200;                             using (StreamWriter writer = new StreamWriter(httpListenerContext.Response.OutputStream))                            {                                writer.WriteLine("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/><title>测试服务器</title></head><body>");                                writer.WriteLine("<div style=\"height:20px;color:blue;text-align:center;\"><p> hello</p></div>");                                writer.WriteLine("<ul>");                                writer.WriteLine("</ul>");                                writer.WriteLine("</body></html>");                                                                }                                            }                })).Start();

HttpListener:使用HttpListener可创建响应 HTTP 请求的简单 HTTP 协议侦听器。实际上HttpListener只是实现了服务器端Socket上面的一个简单封装类。通过设置Prefixes属性来进行侦听,如,侦听器绑定到http或https端点的URL(如下代码).侦听器默认是绑定到运行在http的80端口和https的443的端口,并允许匿名和无身份验证的客户端访问。可以使用HttpListener类的属性Prefixes来制定自定义url和端口,并通过设置属性AuthenticationSchemes属性来配置身份验证。

 建立HttpListener后,执行Start(执行是Start实际上是引发底层的Bind和Listener),就开始处理客服端输入请求。HttpListener中GetContext和套接字的Accept类似,它在没有请求准备好处理的时候处于被阻塞状态。GetContext返回一个对象HttpListenerContext。HttpListenerContext对象的属性Request属性提供了许多关于客户机的一些请求信息.Response则返回一个HttpListerResponse对象,该对象可以用来响应客户机的请求。

AuthenticationSchemes枚举类有以下值:

  Anonymous:默认值,允许任意的客户机进行连接,不需要身份验证。

  Basic:要求提供纯文本(64位编码)用户名和密码来进行验证。

  Digest:类似与基本身份验证,但是用户名和密码使用一个简单密码散列进行传输。

  Ntlm: 指定 NTLM 身份验证(只有IE支持)。

  IntegratedWindowsAuthentication:指定Windows身份验证。

  Negotiate: 和客户端协商以确定身份验证方案。如果客户端和服务器均支持 Kerberos,则使用 Kerberos;否则使用 Ntlm

  None:不进行身份验证。

2. GET方法

publicstaticstring GetUrltoHtml(string Url,string type)        {            try            {                System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url);                // Get the response instance.                System.Net.WebResponse wResp = wReq.GetResponse();                System.IO.Stream respStream = wResp.GetResponseStream();                // Dim reader As StreamReader = New StreamReader(respStream)                using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type)))                {                    return reader.ReadToEnd();                }            }            catch (System.Exception ex)            {                //errorMsg = ex.Message;            }            return"";        }
3.异步

  1. //HttpListener 只支援win2003及xp哦~   
  2. public class HttpServer  
  3. {  
  4.     protected HttpListener Listener;  
  5.     protected bool IsStarted = false;  
  6.   
  7.     //使用傳入一個URI String 例如http://127.0.0.1:8080/ 來開始一個我們的HttpServer  
  8.     public void Start(string strUrl)  
  9.     {  
  10.         if (IsStarted) //已經再Listen就直接Return  
  11.             return;  
  12.   
  13.         if (Listener == null)  
  14.             Listener = new HttpListener();  
  15.   
  16.         //使用傳入的URI String 例如http://127.0.0.1:8080/  
  17.         Listener.Prefixes.Add(strUrl);  
  18.   
  19.         IsStarted = true;  
  20.         Listener.Start(); //開始Listen  
  21.   
  22.         //以非同步方式取得Context  
  23.         IAsyncResult result = this.Listener.BeginGetContext(  
  24.           new AsyncCallback(WebRequestCallback), this.Listener);  
  25.     }  
  26.   
  27.     //停止我們的HttpServer  
  28.     public void Stop()  
  29.     {  
  30.         if (Listener != null)  
  31.         {  
  32.             Listener.Close();  
  33.             Listener = null;  
  34.             IsStarted = false;  
  35.         }  
  36.     }  
  37.   
  38.     //有個Web需求進來  
  39.     private void WebRequestCallback(IAsyncResult result)  
  40.     {  
  41.         //如果Http Server已經停止則不理會  
  42.         if (Listener == null)  
  43.             return;  
  44.   
  45.         //取得Context  
  46.         HttpListenerContext Context = this.Listener.EndGetContext(result);  
  47.   
  48.         //立即開始另一個非同步取得Context  
  49.         Listener.BeginGetContext(new AsyncCallback(WebRequestCallback), this.Listener);  
  50.   
  51.         //處理我們的Web需求  
  52.         ProcessRequest(Context);  
  53.     }  
  54.   
  55.     //處理我們的Web需求  
  56.     private void ProcessRequest(System.Net.HttpListenerContext Context)  
  57.     {  
  58.         Stream request = Context.Request.InputStream;  
  59.        
  60.         string input = null;  
  61.         using (StreamReader sr = new StreamReader(request)) {  
  62.             input = sr.ReadToEnd();  
  63.         }  
  64.         Console.WriteLine(input);  
  65.     }  
  66. }  


实现方法二:

http://www.cnblogs.com/uu102/archive/2013/02/16/2913410.html


参考:http://blog.sina.com.cn/s/blog_6f3ff2c90101wwh5.html

       http://blog.csdn.net/dannywj1371/article/details/8202828

       http://blog.sina.com.cn/s/blog_6f3ff2c90101wwh5.html

       https://msdn.microsoft.com/zh-cn/library/system.net.httplistener.aspx

0 0
原创粉丝点击