This article is a mirror article of machine translation, please click here to jump to the original article.

View: 20804|Reply: 0

[Source] .net implements a simple web server using HttpListener

[Copy link]
Posted on 12/8/2015 2:55:12 PM | | | |


To further simplify the listener for the Http protocol, .net provides us with the HttpListener class, which (System.Net with the namespace) .net encapsulates a series of tasks that handle the Http protocol.

Let's take a look at the definition in MSDN first:

Note: This class is new in .NET Framework version 2.0.



Provides a simple, programmable, and controllable HTTP protocol listener. It is impossible to inherit such a class.

Usage:

public sealed class HttpListener : IDisposable
Note: This class can only be used on Win xp or Win Server 2003 or later operating systems, because this class must use Http.sys system components to get the job done.
Therefore, you should first judge whether this class is supported before using it

  1. / 检查系统是否支持
  2.             if (!HttpListener.IsSupported)
  3.             {
  4.                 throw new System.InvalidOperationException(
  5.                     "使用 HttpListener 必须为 Windows XP SP2 或 Server 2003 以上系统!");
  6.             }
Copy code
2. The Start() method allows this instance to accept incoming requests. Listen immediately

3. Stop() method closes the HttpListener object after processing all currently queued requests

4. The GetContext() method waits for the incoming request to return when it receives the request Just like the Socket implementation server in the previous article, there is an Accept() method, both of which are almost waiting for incoming requests, and the GetContext() method will also block the thread, and when the client's request arrives, it will return an HttpListenerContext object to process the request sent by the client.
    4.1 Request Obtain the HttpListenerRequest object that represents the client resource.

          4.1.1 AcceptType Obtains the MIME type accepted by the client.
4.1.2 UserLanguages Obtain language information.
          4.1.3 UserAgent obtains the user agent provided by the client.
          4.1.4 Headers Get a collection of header name/value pairs sent in a request ---> get a property that is not provided by the HttpListenerRequest class.

4.2 Response This property gets an HttpListenerResponse object, which will be sent to the client in response to the client's request.

4.2.1 ContextLength64 Gets or sets the number of bytes of body data included in the response.
          4.2.2 ContextType Gets or sets the MIME type of the returned content.

The content of the response message body is sent to the client browser by streaming.


  1. //HTTP监听
  2. private HttpListener listeren = new HttpListener();


  3.         #region 监听命令显示窗体
  4.         /// <summary>
  5.         /// 开启监听
  6.         /// </summary>
  7.         private void Init()
  8.         {
  9.             try
  10.             {
  11.                 //指定身份验证 Anonymous匿名访问
  12.                 listeren.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
  13.                 //创建IP地址
  14.                 IPAddress address = IPAddress.Parse(127.0.0.1);
  15.                 listeren.Prefixes.Add("http://" + address + ":30001/");
  16.                 listeren.Start();
  17.                 Thread threadlistener = new Thread(new ThreadStart(ThreadStartListener));
  18.                 threadlistener.Start();
  19.                 MessageBox.Show("监听成功");
  20.             }
  21.             catch (Exception ex)
  22.             {
  23.                 cfg.Logs.Add(new LogClass { LogStr = "HttpListener error", ExInfo = ex });
  24.             }
  25.         }
  26.         
  27.          /// <summary>
  28.         /// 监听连接线程
  29.         /// </summary>
  30.         private void ThreadStartListener()
  31.         {
  32.             try
  33.             {
  34.                 while (true)
  35.             {
  36.                 // 注意: GetContext 方法将阻塞线程,直到请求到达
  37.                 HttpListenerContext context = listeren.GetContext();
  38.                 // 取得请求对象
  39.                 HttpListenerRequest request = context.Request;
  40.                 Console.WriteLine("{0} {1} HTTP/1.1", request.HttpMethod, request.RawUrl);
  41.                 Console.WriteLine("Accept: {0}", string.Join(",", request.AcceptTypes));
  42.                 Console.WriteLine("Accept-Language: {0}",
  43.                     string.Join(",", request.UserLanguages));
  44.                 Console.WriteLine("User-Agent: {0}", request.UserAgent);
  45.                 Console.WriteLine("Accept-Encoding: {0}", request.Headers["Accept-Encoding"]);
  46.                 Console.WriteLine("Connection: {0}",
  47.                     request.KeepAlive ? "Keep-Alive" : "close");
  48.                 Console.WriteLine("Host: {0}", request.UserHostName);
  49.                 Console.WriteLine("Pragma: {0}", request.Headers["Pragma"]);
  50.                 // 取得回应对象
  51.                 HttpListenerResponse response = context.Response;
  52.                 // 构造回应内容
  53.                 string responseString
  54.                     = @"<html>
  55.                         <head><title>From HttpListener Server</title></head>
  56.                         <body><h1>Hello, 码农网(www.itsvse.com).</h1></body>
  57.                         </html>";
  58.                 // 设置回应头部内容,长度,编码
  59.                 response.ContentLength64
  60.                     = System.Text.Encoding.UTF8.GetByteCount(responseString);
  61.                 response.ContentType = "text/html; charset=UTF-8";
  62.                 // 输出回应内容
  63.                 System.IO.Stream output = response.OutputStream;
  64.                 System.IO.StreamWriter writer = new System.IO.StreamWriter(output);
  65.                 writer.Write(responseString);
  66.                 // 必须关闭输出流
  67.                 writer.Close();
  68.             }
  69.             }
  70.             catch (Exception ex)
  71.             {
  72.                 cfg.Logs.Add(new LogClass { LogStr = "HttpListener error", ExInfo = ex });
  73.             }
  74.         }
  75.         #endregion
Copy code







Previous:WPF closes windows and processes
Next:Let your WPF program render Win8 style themes under Win7
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com