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
- / 检查系统是否支持
- if (!HttpListener.IsSupported)
- {
- throw new System.InvalidOperationException(
- "使用 HttpListener 必须为 Windows XP SP2 或 Server 2003 以上系统!");
- }
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.
- //HTTP监听
- private HttpListener listeren = new HttpListener();
- #region 监听命令显示窗体
- /// <summary>
- /// 开启监听
- /// </summary>
- private void Init()
- {
- try
- {
- //指定身份验证 Anonymous匿名访问
- listeren.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
- //创建IP地址
- IPAddress address = IPAddress.Parse(127.0.0.1);
- listeren.Prefixes.Add("http://" + address + ":30001/");
- listeren.Start();
- Thread threadlistener = new Thread(new ThreadStart(ThreadStartListener));
- threadlistener.Start();
- MessageBox.Show("监听成功");
- }
- catch (Exception ex)
- {
- cfg.Logs.Add(new LogClass { LogStr = "HttpListener error", ExInfo = ex });
- }
- }
-
- /// <summary>
- /// 监听连接线程
- /// </summary>
- private void ThreadStartListener()
- {
- try
- {
- while (true)
- {
- // 注意: GetContext 方法将阻塞线程,直到请求到达
- HttpListenerContext context = listeren.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-Language: {0}",
- string.Join(",", request.UserLanguages));
- Console.WriteLine("User-Agent: {0}", request.UserAgent);
- Console.WriteLine("Accept-Encoding: {0}", request.Headers["Accept-Encoding"]);
- Console.WriteLine("Connection: {0}",
- request.KeepAlive ? "Keep-Alive" : "close");
- Console.WriteLine("Host: {0}", request.UserHostName);
- Console.WriteLine("Pragma: {0}", request.Headers["Pragma"]);
- // 取得回应对象
- HttpListenerResponse response = context.Response;
- // 构造回应内容
- string responseString
- = @"<html>
- <head><title>From HttpListener Server</title></head>
- <body><h1>Hello, 码农网(www.itsvse.com).</h1></body>
- </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();
- }
- }
- catch (Exception ex)
- {
- cfg.Logs.Add(new LogClass { LogStr = "HttpListener error", ExInfo = ex });
- }
- }
- #endregion
Copy code
|