Per semplificare ulteriormente l'ascoltatore del protocollo Http, .net ci fornisce la classe HttpListener, che (System.Net con il namespace) .net racchiude una serie di compiti che gestiscono il protocollo Http.
Diamo prima un'occhiata alla definizione in MSDN:
Nota: Questa classe è nuova in .NET Framework versione 2.0.
Fornisce un listener di protocollo HTTP semplice, programmabile e controllabile. È impossibile ereditare una tale classe.
Uso:
Classe pubblica sigillata HttpListener : IDisposable Nota: Questa classe può essere utilizzata solo su Windows XP o sui sistemi operativi Win Server 2003 o successivi, perché deve utilizzare Http.sys componenti di sistema per svolgere il compito. Pertanto, dovresti prima giudicare se questa classe è supportata prima di usarla
- / 检查系统是否支持
- if (!HttpListener.IsSupported)
- {
- throw new System.InvalidOperationException(
- "使用 HttpListener 必须为 Windows XP SP2 或 Server 2003 以上系统!");
- }
Copia codice 2. Il metodo Start() permette a questa istanza di accettare richieste in arrivo. Ascolta subito
3. Il metodo Stop() chiude l'oggetto HttpListener dopo aver elaborato tutte le richieste attualmente in coda
4. Il metodo GetContext() attende che la richiesta in ingresso ritorni quando riceve la richiesta Proprio come il server di implementazione Socket nell'articolo precedente, esiste un metodo Accept(), entrambi quasi in attesa di richieste in arrivo, e il metodo GetContext() bloccherà anch'esso il thread, e quando arriva la richiesta del client, restituirà un oggetto HttpListenerContext per elaborare la richiesta inviata dal client. 4.1 Richiedi Ottenere l'oggetto HttpListenerRequest che rappresenta la risorsa client.
4.1.1 AcceptType ottiene il tipo MIME accettato dal cliente. 4.1.2 Linguaggi utente Ottieni informazioni sulla lingua. 4.1.3 UserAgent ottiene l'user agent fornito dal client. 4.1.4 Header Ricevi una raccolta di coppie nome/valore intestazione inviate in una richiesta ---> ottieni una proprietà non fornita dalla classe HttpListenerRequest.
4.2 Risposta Questa proprietà ottiene un oggetto HttpListenerResponse, che verrà inviato al client in risposta alla richiesta del cliente.
4.2.1 ContextLongezza64 Riceve o imposta il numero di byte di dati corporei inclusi nella risposta. 4.2.2 ContextType Ottiene o imposta il tipo MIME del contenuto restituito.
Il contenuto del corpo del messaggio di risposta viene inviato al browser client tramite 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
Copia codice
|