HttpListener Clase

Definición

Proporciona un agente de escucha de protocolo HTTP simple y controlado mediante programación. Esta clase no puede heredarse.

public ref class HttpListener sealed : IDisposable
public sealed class HttpListener : IDisposable
type HttpListener = class
    interface IDisposable
Public NotInheritable Class HttpListener
Implements IDisposable
Herencia
HttpListener
Implementaciones

Ejemplos

// 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

Comentarios

Para obtener más información sobre esta API, consulte Comentarios complementarios de api para HttpListener.

Constructores

Nombre Description
HttpListener()

Inicializa una nueva instancia de la clase HttpListener.

Propiedades

Nombre Description
AuthenticationSchemes

Obtiene o establece el esquema usado para autenticar a los clientes.

AuthenticationSchemeSelectorDelegate

Obtiene o establece el delegado al que se llama para determinar el protocolo utilizado para autenticar a los clientes.

DefaultServiceNames

Obtiene una lista predeterminada de nombres de proveedor de servicios (SPN) determinados por prefijos registrados.

ExtendedProtectionPolicy

Obtiene o establece el objeto ExtendedProtectionPolicy que se va a usar para la protección ampliada para una sesión.

ExtendedProtectionSelectorDelegate

Obtiene o establece el delegado al que se llama para determinar el que ExtendedProtectionPolicy se va a usar para cada solicitud.

IgnoreWriteExceptions

Obtiene o establece un Boolean valor que especifica si la aplicación recibe excepciones que se producen cuando un HttpListener envía la respuesta al cliente.

IsListening

Obtiene un valor que indica si HttpListener se ha iniciado.

IsSupported

Obtiene un valor que indica si HttpListener se puede usar con el sistema operativo actual.

Prefixes

Obtiene los prefijos del identificador uniforme de recursos (URI) que controla este HttpListener objeto.

Realm

Obtiene o establece el dominio kerberos o la partición de recursos, asociados a este HttpListener objeto.

TimeoutManager

El administrador de tiempo de espera de esta HttpListener instancia.

UnsafeConnectionNtlmAuthentication

Obtiene o establece un Boolean valor que controla si, cuando se usa NTLM, se requieren solicitudes adicionales que usen la misma conexión del Protocolo de control de transmisión (TCP) para autenticarse.

Métodos

Nombre Description
Abort()

Cierra el HttpListener objeto inmediatamente, descartando todas las solicitudes actualmente en cola.

BeginGetContext(AsyncCallback, Object)

Comienza a recuperar de forma asincrónica una solicitud entrante.

Close()

Cierra el HttpListener.

EndGetContext(IAsyncResult)

Completa una operación asincrónica para recuperar una solicitud de cliente entrante.

Equals(Object)

Determina si el objeto especificado es igual al objeto actual.

(Heredado de Object)
GetContext()

Espera una solicitud entrante y devuelve cuando se recibe una.

GetContextAsync()

Espera una solicitud entrante como una operación asincrónica.

GetHashCode()

Actúa como la función hash predeterminada.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
MemberwiseClone()

Crea una copia superficial del Objectactual.

(Heredado de Object)
Start()

Permite que esta instancia reciba solicitudes entrantes.

Stop()

Hace que esta instancia deje de recibir nuevas solicitudes entrantes y finalice el procesamiento de todas las solicitudes en curso.

ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Implementaciones de interfaz explícitas

Nombre Description
IDisposable.Dispose()

Libera los recursos mantenidos por este HttpListener objeto.

Se aplica a

Consulte también