HttpListener Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Fornece um ouvinte simples de protocolo HTTP controlado programaticamente. Esta classe não pode ser herdada.
public ref class HttpListener sealed : IDisposable
public sealed class HttpListener : IDisposable
type HttpListener = class
interface IDisposable
Public NotInheritable Class HttpListener
Implements IDisposable
- Herança
-
HttpListener
- Implementações
Exemplos
// This example requires the System and System.Net namespaces.
public static void SimpleListenerExample(string[] prefixes)
{
if (!HttpListener.IsSupported)
{
Console.WriteLine ("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
return;
}
// URI prefixes are required,
// for example "http://contoso.com:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
Console.WriteLine("Listening...");
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer,0,buffer.Length);
// You must close the output stream.
output.Close();
listener.Stop();
}
Public Shared Sub SimpleListenerExample(prefixes As String())
If Not HttpListener.IsSupported Then
Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.")
Return
End If
' URI prefixes are required,
' for example "http://contoso.com:8080/index/".
If prefixes Is Nothing Or prefixes.Length = 0 Then
Throw New ArgumentException("prefixes")
End If
' Create a listener
Dim listener = New HttpListener()
For Each s As String In prefixes
listener.Prefixes.Add(s)
Next
listener.Start()
Console.WriteLine("Listening...")
' Note: The GetContext method blocks while waiting for a request.
Dim context As HttpListenerContext = listener.GetContext()
Console.WriteLine("Listening...")
' Obtain a response object
Dim request As HttpListenerRequest = context.Request
' Construct a response.
Dim response As HttpListenerResponse = context.Response
Dim responseString As String = "<HTML><BODY> Hello world!</BODY></HTML>"
Dim buffer As Byte() = System.Text.Encoding.UTF8.GetBytes(responseString)
' Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length
Dim output As System.IO.Stream = response.OutputStream
output.Write(buffer, 0, buffer.Length)
'You must close the output stream.
output.Close()
listener.Stop()
End Sub
Observações
Para mais informações sobre esta API, consulte Observações suplementares da API para o HttpListener.
Construtores
| Name | Description |
|---|---|
| HttpListener() |
Inicializa uma nova instância da HttpListener classe. |
Propriedades
| Name | Description |
|---|---|
| AuthenticationSchemes |
Obtém ou define o esquema usado para autenticar clientes. |
| AuthenticationSchemeSelectorDelegate |
Recebe ou define o delegado chamado para determinar o protocolo usado para autenticar clientes. |
| DefaultServiceNames |
Recebe uma lista padrão de Nomes de Prestadores de Serviço (SPNs) conforme determinado pelos prefixos registados. |
| ExtendedProtectionPolicy |
Obtém ou configuram o ExtendedProtectionPolicy para usar para proteção prolongada durante uma sessão. |
| ExtendedProtectionSelectorDelegate |
Obtém ou define o delegado chamado para determinar o ExtendedProtectionPolicy a usar para cada pedido. |
| IgnoreWriteExceptions |
Recebe ou define um Boolean valor que especifica se a sua aplicação recebe exceções que ocorrem quando envia HttpListener a resposta ao cliente. |
| IsListening |
Obtém um valor que indica se HttpListener já foi iniciado. |
| IsSupported |
Recebe um valor que indica se HttpListener pode ser usado com o sistema operativo atual. |
| Prefixes |
Obtém os prefixos Uniform Resource Identifier (URI) tratados por este HttpListener objeto. |
| Realm |
Obtém ou define o reino, ou partição de recursos, associado a este HttpListener objeto. |
| TimeoutManager |
O gestor de tempo para este HttpListener caso. |
| UnsafeConnectionNtlmAuthentication |
Recebe ou define um Boolean valor que controla se, quando o NTLM é utilizado, são necessários pedidos adicionais usando a mesma ligação ao Protocolo de Controlo de Transmissão (TCP) para autenticação. |
Métodos
| Name | Description |
|---|---|
| Abort() |
Desliga imediatamente o HttpListener objeto, descartando todos os pedidos atualmente em fila. |
| BeginGetContext(AsyncCallback, Object) |
Começa a recuperar de forma assíncrona um pedido recebido. |
| Close() |
Desliga o HttpListenerarquivo . |
| EndGetContext(IAsyncResult) |
Conclui uma operação assíncrona para recuperar um pedido de cliente recebido. |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetContext() |
Aguarda um pedido recebido e devolve quando um é recebido. |
| GetContextAsync() |
Aguarda um pedido recebido como uma operação assíncrona. |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| Start() |
Permite que esta instância receba pedidos recebidos. |
| Stop() |
Faz com que esta instância deixe de receber novos pedidos recebidos e termina o processamento de todos os pedidos em andamento. |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |
Implementações de Interface Explícita
| Name | Description |
|---|---|
| IDisposable.Dispose() |
Liberta os recursos detidos por este HttpListener objeto. |