Compartir a través de


HttpChannel Clase

Definición

Implementa un canal de cliente para llamadas remotas que usa el protocolo HTTP para transmitir mensajes.

public ref class HttpChannel : System::Runtime::Remoting::Channels::BaseChannelWithProperties, System::Runtime::Remoting::Channels::IChannelReceiver, System::Runtime::Remoting::Channels::IChannelReceiverHook, System::Runtime::Remoting::Channels::IChannelSender
public ref class HttpChannel : System::Runtime::Remoting::Channels::BaseChannelWithProperties, System::Runtime::Remoting::Channels::IChannelReceiver, System::Runtime::Remoting::Channels::IChannelReceiverHook, System::Runtime::Remoting::Channels::IChannelSender, System::Runtime::Remoting::Channels::ISecurableChannel
public class HttpChannel : System.Runtime.Remoting.Channels.BaseChannelWithProperties, System.Runtime.Remoting.Channels.IChannelReceiver, System.Runtime.Remoting.Channels.IChannelReceiverHook, System.Runtime.Remoting.Channels.IChannelSender
public class HttpChannel : System.Runtime.Remoting.Channels.BaseChannelWithProperties, System.Runtime.Remoting.Channels.IChannelReceiver, System.Runtime.Remoting.Channels.IChannelReceiverHook, System.Runtime.Remoting.Channels.IChannelSender, System.Runtime.Remoting.Channels.ISecurableChannel
type HttpChannel = class
    inherit BaseChannelWithProperties
    interface IChannelReceiver
    interface IChannelSender
    interface IChannel
    interface IChannelReceiverHook
type HttpChannel = class
    inherit BaseChannelWithProperties
    interface IChannelReceiver
    interface IChannelSender
    interface IChannel
    interface IChannelReceiverHook
    interface ISecurableChannel
type HttpChannel = class
    inherit BaseChannelWithProperties
    interface IChannelReceiver
    interface IChannel
    interface IChannelSender
    interface IChannelReceiverHook
    interface ISecurableChannel
Public Class HttpChannel
Inherits BaseChannelWithProperties
Implements IChannelReceiver, IChannelReceiverHook, IChannelSender
Public Class HttpChannel
Inherits BaseChannelWithProperties
Implements IChannelReceiver, IChannelReceiverHook, IChannelSender, ISecurableChannel
Herencia
Implementaciones

Ejemplos

En el ejemplo de código siguiente se muestra cómo usar para HttpClientChannel configurar un servidor remoto y su cliente. El ejemplo contiene tres partes:

  • Un servidor

  • Un cliente

  • Objeto remoto utilizado por el servidor y el cliente

En el ejemplo de código siguiente se muestra un servidor.

#using <System.dll>
#using <System.Runtime.Remoting.dll>
#using "common.dll"
using namespace System;
using namespace System::Runtime::Remoting;
using namespace System::Runtime::Remoting::Channels;
using namespace System::Runtime::Remoting::Channels::Http;

void main()
{
   // Create the server channel.
   HttpServerChannel^ serverChannel = gcnew HttpServerChannel( 9090 );
   
   // Register the server channel.
   ChannelServices::RegisterChannel( serverChannel );
   
   // Expose an object for remote calls.
   RemotingConfiguration::RegisterWellKnownServiceType( RemoteObject::typeid, L"RemoteObject.rem", WellKnownObjectMode::Singleton );
   
   // Wait for the user prompt.
   Console::WriteLine( L"Press ENTER to exit the server." );
   Console::ReadLine();
   Console::WriteLine( L"The server is exiting." );
}
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;

public class Server
{
    public static void Main(string[] args)
    {
        // Create the server channel.
        HttpServerChannel serverChannel = new HttpServerChannel(9090);

        // Register the server channel.
        ChannelServices.RegisterChannel(serverChannel);

        // Expose an object for remote calls.
        RemotingConfiguration.RegisterWellKnownServiceType(
            typeof(RemoteObject), "RemoteObject.rem",
            WellKnownObjectMode.Singleton);

        // Wait for the user prompt.
        Console.WriteLine("Press ENTER to exit the server.");
        Console.ReadLine();
        Console.WriteLine("The server is exiting.");
    }
}

En el ejemplo de código siguiente se muestra un cliente para este servidor.

#using <System.dll>
#using <System.Runtime.Remoting.dll>
#using "common.dll"

using namespace System;
using namespace System::Runtime::Remoting;
using namespace System::Runtime::Remoting::Channels;
using namespace System::Runtime::Remoting::Channels::Http;
void main()
{
   // Create the channel.
   HttpClientChannel^ clientChannel = gcnew HttpClientChannel;

   // Register the channel.
   ChannelServices::RegisterChannel( clientChannel );

   // Register as client for remote object.
   WellKnownClientTypeEntry^ remoteType = gcnew WellKnownClientTypeEntry( RemoteObject::typeid,L"http://localhost:9090/RemoteObject.rem" );
   RemotingConfiguration::RegisterWellKnownClientType( remoteType );

   // Create a message sink.
   String^ objectUri;
   System::Runtime::Remoting::Messaging::IMessageSink^ messageSink = clientChannel->CreateMessageSink( L"http://localhost:9090/RemoteObject.rem", nullptr,  objectUri );
   Console::WriteLine( L"The URI of the message sink is {0}.", objectUri );
   if ( messageSink != nullptr )
   {
      Console::WriteLine( L"The type of the message sink is {0}.", messageSink->GetType() );
   }

   // Display the channel's properties using Keys and Item.
   for each(String^ key in clientChannel->Keys)
   {
       Console::WriteLine("clientChannel[{0}] = <{1}>", key, clientChannel[key]);
   }

   // Parse the channel's URI.
   String^ objectUrl = L"http://localhost:9090/RemoteObject.rem";
   String^ channelUri = clientChannel->Parse( objectUrl,  objectUri );
   Console::WriteLine( L"The object URL is {0}.", objectUrl );
   Console::WriteLine( L"The object URI is {0}.", objectUri );
   Console::WriteLine( L"The channel URI is {0}.", channelUri );

   // Create an instance of the remote object.
   RemoteObject^ service = gcnew RemoteObject;
   
   // Invoke a method on the remote object.
   Console::WriteLine( L"The client is invoking the remote object." );
   Console::WriteLine( L"The remote object has been called {0} times.", service->GetCount() );
}
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;

public class Client
{
    public static void Main(string[] args)
    {
        // Create the channel.
        HttpClientChannel clientChannel = new HttpClientChannel();

        // Register the channel.
        ChannelServices.RegisterChannel(clientChannel);

        // Register as client for remote object.
        WellKnownClientTypeEntry remoteType =
            new WellKnownClientTypeEntry(typeof(RemoteObject),
            "http://localhost:9090/RemoteObject.rem");
        RemotingConfiguration.RegisterWellKnownClientType(remoteType);

        // Create a message sink.
        string objectUri;
        System.Runtime.Remoting.Messaging.IMessageSink messageSink =
            clientChannel.CreateMessageSink(
            "http://localhost:9090/RemoteObject.rem",
            null, out objectUri);
        Console.WriteLine(
            "The URI of the message sink is {0}.",
            objectUri);
        if (messageSink != null)
        {
            Console.WriteLine("The type of the message sink is {0}.",
                messageSink.GetType().ToString());
        }

        // Display the channel's properties using Keys and Item.
        foreach(string key in clientChannel.Keys)
        {
            Console.WriteLine(
                "clientChannel[{0}] = <{1}>",
                key, clientChannel[key]);
        }

        // Parse the channel's URI.
        string objectUrl = "http://localhost:9090/RemoteObject.rem";
        string channelUri = clientChannel.Parse(objectUrl, out objectUri);
        Console.WriteLine("The object URL is {0}.", objectUrl);
        Console.WriteLine("The object URI is {0}.", objectUri);
        Console.WriteLine("The channel URI is {0}.", channelUri);

        // Create an instance of the remote object.
        RemoteObject service = new RemoteObject();

        // Invoke a method on the remote object.
        Console.WriteLine("The client is invoking the remote object.");
        Console.WriteLine("The remote object has been called {0} times.",
            service.GetCount());
    }
}

En el ejemplo de código siguiente se muestra el objeto remoto utilizado por el servidor y el cliente.

#using <System.dll>
using namespace System;
using namespace System::Runtime::Remoting;

// Remote object.
public ref class RemoteObject: public MarshalByRefObject
{
private:
   static int callCount = 0;

public:
   int GetCount()
   {
      Console::WriteLine( L"GetCount was called." );
      callCount++;
      return (callCount);
   }

};
using System;
using System.Runtime.Remoting;

// Remote object.
public class RemoteObject : MarshalByRefObject
{
    private int callCount = 0;

    public int GetCount()
    {
        Console.WriteLine("GetCount was called.");
        callCount++;
        return(callCount);
    }
}

Comentarios

Importante

Llamar a métodos de esta clase con datos que no son de confianza es un riesgo de seguridad. Llame a los métodos de esta clase solo con datos de confianza. Para obtener más información, vea Validar todas las entradas.

Canales transporta mensajes a través de límites de comunicación remota (por ejemplo, entre equipos o dominios de aplicación). La HttpChannel clase transporta mensajes mediante el protocolo HTTP.

La infraestructura remota de .NET Framework usa canales para transportar llamadas remotas. Cuando un cliente realiza una llamada a un objeto remoto, la llamada se serializa en un mensaje enviado por un canal de cliente y recibido por un canal de servidor. A continuación, se deserializa y se procesa. Los valores devueltos se transmiten por el canal del servidor y los recibe el canal de cliente.

Un HttpChannel objeto tiene propiedades de configuración asociadas que se pueden establecer en tiempo de ejecución en un archivo de configuración (invocando el método estático RemotingConfiguration.Configure ) o mediante programación (pasando una IDictionary colección al HttpChannel constructor).

Constructores

Nombre Description
HttpChannel()

Inicializa una nueva instancia de la clase HttpChannel.

HttpChannel(IDictionary, IClientChannelSinkProvider, IServerChannelSinkProvider)

Inicializa una nueva instancia de la HttpChannel clase con las propiedades y receptores de configuración especificados.

HttpChannel(Int32)

Inicializa una nueva instancia de la HttpChannel clase con un canal de servidor que escucha en el puerto especificado.

Campos

Nombre Description
SinksWithProperties

Indica el receptor de canal superior en la pila del receptor del canal.

(Heredado de BaseChannelWithProperties)

Propiedades

Nombre Description
ChannelData

Obtiene los datos específicos del canal.

ChannelName

Obtiene el nombre del canal actual.

ChannelPriority

Obtiene la prioridad del canal actual.

ChannelScheme

Obtiene el tipo de agente de escucha al que enlazar (por ejemplo, "http").

ChannelSinkChain

Obtiene la cadena de receptores del canal que usa el canal actual.

Count

Obtiene el número de propiedades asociadas al objeto channel.

(Heredado de BaseChannelObjectWithProperties)
IsFixedSize

Obtiene un valor que indica si el número de propiedades que se pueden escribir en el objeto de canal es fijo.

(Heredado de BaseChannelObjectWithProperties)
IsReadOnly

Obtiene un valor que indica si la colección de propiedades del objeto de canal es de solo lectura.

(Heredado de BaseChannelObjectWithProperties)
IsSecured

Obtiene o establece un valor booleano que indica si el canal actual es seguro.

IsSynchronized

Obtiene un valor que indica si el diccionario de propiedades del objeto de canal está sincronizado.

(Heredado de BaseChannelObjectWithProperties)
Item[Object]

Devuelve la propiedad de canal especificada.

Keys

Obtiene una ICollection de las claves a las que están asociadas las propiedades del canal.

Properties

Obtiene una IDictionary de las propiedades del canal asociadas al canal actual.

SyncRoot

Obtiene un objeto que se usa para sincronizar el acceso a .BaseChannelObjectWithProperties

(Heredado de BaseChannelObjectWithProperties)
Values

Obtiene un ICollection de los valores de las propiedades asociadas al objeto channel.

(Heredado de BaseChannelObjectWithProperties)
WantsToListen

Obtiene un valor booleano que indica si la instancia actual quiere enlazarse al servicio de escucha externo.

Métodos

Nombre Description
Add(Object, Object)

Genera una NotSupportedException.

(Heredado de BaseChannelObjectWithProperties)
AddHookChannelUri(String)

Agrega un URI en el que el enlace de canal debe escuchar.

Clear()

Genera una NotSupportedException.

(Heredado de BaseChannelObjectWithProperties)
Contains(Object)

Devuelve un valor que indica si el objeto de canal contiene una propiedad asociada a la clave especificada.

(Heredado de BaseChannelObjectWithProperties)
CopyTo(Array, Int32)

Genera una NotSupportedException.

(Heredado de BaseChannelObjectWithProperties)
CreateMessageSink(String, Object, String)

Devuelve un receptor de mensajes de canal que entrega mensajes a la dirección URL o al objeto de datos del canal especificados.

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
GetEnumerator()

Devuelve un IDictionaryEnumerator objeto que enumera todas las propiedades asociadas al objeto channel.

(Heredado de BaseChannelObjectWithProperties)
GetHashCode()

Sirve como función hash predeterminada.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
GetUrlsForUri(String)

Devuelve una matriz de todas las direcciones URL de un objeto con el URI especificado, hospedado en el objeto actual HttpChannel.

MemberwiseClone()

Crea una copia superficial del Objectactual.

(Heredado de Object)
Parse(String, String)

Extrae el URI del canal y el URI del objeto conocido remoto de la dirección URL especificada.

Remove(Object)

Genera una NotSupportedException.

(Heredado de BaseChannelObjectWithProperties)
StartListening(Object)

Indica al canal actual que empiece a escuchar las solicitudes.

StopListening(Object)

Indica al canal actual que deje de escuchar solicitudes.

ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Implementaciones de interfaz explícitas

Nombre Description
IEnumerable.GetEnumerator()

Devuelve un IEnumerator objeto que enumera todas las propiedades asociadas al objeto channel.

(Heredado de BaseChannelObjectWithProperties)

Métodos de extensión

Nombre Description
AsParallel(IEnumerable)

Habilita la paralelización de una consulta.

AsQueryable(IEnumerable)

Convierte un IEnumerable en un IQueryable.

Cast<TResult>(IEnumerable)

Convierte los elementos de un IEnumerable al tipo especificado.

OfType<TResult>(IEnumerable)

Filtra los elementos de un IEnumerable en función de un tipo especificado.

Se aplica a