HttpChannel Clase

Definición

Implementa un canal de cliente para llamadas remotas que utiliza el protocolo HTTP para transmitir los 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 de comunicación remota 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 supone 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.

Los canales transportan mensajes entre 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 de comunicación 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 procesa. Los valores devueltos se transmiten por el canal de 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). Para obtener una lista de estas propiedades de configuración, vea Propiedades de configuración de canal y formateador.

Constructores

HttpChannel()

Inicializa una nueva instancia de la clase HttpChannel.

HttpChannel(IDictionary, IClientChannelSinkProvider, IServerChannelSinkProvider)

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

HttpChannel(Int32)

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

Campos

SinksWithProperties

Indica el receptor de canal superior de la pila de receptores de canales.

(Heredado de BaseChannelWithProperties)

Propiedades

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 que se va a enlazar (por ejemplo, "http").

ChannelSinkChain

Obtiene la cadena de receptores de canal que utiliza el canal actual.

Count

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

(Heredado de BaseChannelObjectWithProperties)
IsFixedSize

Obtiene un valor que indica si el número de propiedades que se pueden especificar 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 actual es de sólo 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 las propiedades de un objeto de canal está sincronizado.

(Heredado de BaseChannelObjectWithProperties)
Item[Object]

Devuelve la propiedad de canal especificada.

Keys

Obtiene una ICollection de claves a la que se asocian las propiedades del canal.

Properties

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

SyncRoot

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

(Heredado de BaseChannelObjectWithProperties)
Values

Obtiene ICollection de los valores de las propiedades asociadas al objeto de canal.

(Heredado de BaseChannelObjectWithProperties)
WantsToListen

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

Métodos

Add(Object, Object)

Produce una excepción NotSupportedException.

(Heredado de BaseChannelObjectWithProperties)
AddHookChannelUri(String)

Agrega el URI en el que el enlace del canal debe permanecer a la escucha.

Clear()

Produce una excepción 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)

Produce una excepción NotSupportedException.

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

Devuelve un receptor de mensajes de canal que envía 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 que enumera todas las propiedades asociadas al objeto de canal.

(Heredado de BaseChannelObjectWithProperties)
GetHashCode()

Sirve como la 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 la dirección URI especificada, hospedadas en el HttpChannel actual.

MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
Parse(String, String)

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

Remove(Object)

Produce una excepción NotSupportedException.

(Heredado de BaseChannelObjectWithProperties)
StartListening(Object)

Indica al canal actual que inicie la escucha de solicitudes.

StopListening(Object)

Indica al canal actual que detenga la escucha de solicitudes.

ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Implementaciones de interfaz explícitas

IEnumerable.GetEnumerator()

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

(Heredado de BaseChannelObjectWithProperties)

Métodos de extensión

Cast<TResult>(IEnumerable)

Convierte los elementos de IEnumerable en el tipo especificado.

OfType<TResult>(IEnumerable)

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

AsParallel(IEnumerable)

Habilita la paralelización de una consulta.

AsQueryable(IEnumerable)

Convierte una interfaz IEnumerable en IQueryable.

Se aplica a

Consulte también