Http 프로토콜의 리스너를 더욱 단순화하기 위해, .net은 HttpListener 클래스를 제공하는데, 이는 (네임스페이스와 System.Net) .net이 Http 프로토콜을 처리하는 일련의 작업을 캡슐화합니다.
먼저 MSDN의 정의를 살펴보겠습니다:
참고: 이 수업은 .NET Framework 버전 2.0에서 새롭게 도입되었습니다.
간단하고 프로그래밍 가능하며 제어 가능한 HTTP 프로토콜 리스너를 제공합니다. 그런 계급을 물려받는 것은 불가능합니다.
사용법:
public sealed class HttpListener : IDisposable 참고: 이 클래스는 Windows XP나 Windows Server 2003 이후 운영체제에서만 사용할 수 있으며, 이 클래스는 작업을 수행하기 위해 Http.sys 시스템 구성 요소를 사용해야 합니다. 따라서 사용하기 전에 이 클래스가 지원되는지 먼저 판단해야 합니다
- / 检查系统是否支持
- if (!HttpListener.IsSupported)
- {
- throw new System.InvalidOperationException(
- "使用 HttpListener 必须为 Windows XP SP2 或 Server 2003 以上系统!");
- }
코드 복사 2. Start() 메서드는 이 인스턴스가 들어오는 요청을 받을 수 있도록 허용합니다. 즉시 들어보세요
3. Stop() 메서드는 현재 대기열에 있는 모든 요청을 처리한 후 HttpListener 객체를 닫습니다
4. GetContext() 메서드는 요청을 받을 때 들어오는 요청이 돌아오기를 기다립니다. 앞서 언급한 소켓 구현 서버와 마찬가지로, Accept() 메서드가 있는데, 두 메서드 모두 거의 들어오는 요청을 기다리고 있습니다. GetContext() 메서드도 스레드를 차단하고, 클라이언트의 요청이 도착하면 클라이언트가 보낸 요청을 처리하기 위해 HttpListenerContext 객체를 반환합니다. 4.1 요청: 클라이언트 리소스를 나타내는 HttpListenerRequest 객체를 얻습니다.
4.1.1 AcceptType은 클라이언트가 수락하는 MIME 유형을 획득합니다. 4.1.2 사용자 언어 정보 획득. 4.1.3 UserAgent는 클라이언트가 제공한 사용자 에이전트를 획득합니다. 4.1.4 헤더 요청에서 보내진 헤더 이름/값 쌍 모음을 받---> HttpListenerRequest 클래스에서 제공하지 않은 속성을 얻습니다.
4.2 응답 이 속성은 클라이언트의 요청에 응답하여 전송되는 HttpListenerResponse 객체를 받습니다.
4.2.1 ContextLength64 응답에 포함된 본문 데이터 바이트 수를 획득하거나 설정합니다. 4.2.2 ContextType은 반환된 콘텐츠의 MIME 유형을 가져가거나 설정합니다.
응답 메시지 본문의 내용은 스트리밍을 통해 클라이언트 브라우저로 전송됩니다.
- //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
코드 복사
|