HttpClientChannel Classe

Definição

Implementa um canal de cliente para chamadas remotas que usa o protocolo HTTP para transmitir mensagens.

public ref class HttpClientChannel : System::Runtime::Remoting::Channels::BaseChannelWithProperties, System::Runtime::Remoting::Channels::IChannelSender
public ref class HttpClientChannel : System::Runtime::Remoting::Channels::BaseChannelWithProperties, System::Runtime::Remoting::Channels::IChannelSender, System::Runtime::Remoting::Channels::ISecurableChannel
public class HttpClientChannel : System.Runtime.Remoting.Channels.BaseChannelWithProperties, System.Runtime.Remoting.Channels.IChannelSender
public class HttpClientChannel : System.Runtime.Remoting.Channels.BaseChannelWithProperties, System.Runtime.Remoting.Channels.IChannelSender, System.Runtime.Remoting.Channels.ISecurableChannel
type HttpClientChannel = class
    inherit BaseChannelWithProperties
    interface IChannelSender
    interface IChannel
type HttpClientChannel = class
    inherit BaseChannelWithProperties
    interface IChannelSender
    interface IChannel
    interface ISecurableChannel
Public Class HttpClientChannel
Inherits BaseChannelWithProperties
Implements IChannelSender
Public Class HttpClientChannel
Inherits BaseChannelWithProperties
Implements IChannelSender, ISecurableChannel
Herança
Implementações

Exemplos

O exemplo de código a seguir mostra como usar um HttpClientChannel servidor de comunicação remota e seu cliente. O exemplo contém três partes:

  • Um servidor

  • Um cliente

  • Um objeto remoto usado pelo servidor e pelo cliente

O exemplo de código a seguir mostra um 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.");
    }
}

O exemplo de código a seguir mostra um 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());
    }
}

O exemplo de código a seguir mostra o objeto remoto usado pelo servidor e pelo 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);
    }
}

Comentários

Importante

Chamar métodos desta classe quando você tiver dados não confiáveis é um risco à segurança. Chame os métodos dessa classe somente quando você tiver dados confiáveis. Para obter mais informações, consulte Validar Todas as Entradas.

Canais transportam mensagens entre limites de comunicação remota (por exemplo, entre computadores ou domínios de aplicativo). A HttpClientChannel classe transporta mensagens usando o protocolo HTTP.

Os canais são usados pela infraestrutura de comunicação remota .NET Framework para transportar chamadas remotas. Quando um cliente faz uma chamada para um objeto remoto, a chamada é serializada em uma mensagem enviada por um canal cliente e recebida por um canal de servidor. Em seguida, ele é desserializado e processado. Todos os valores retornados são transmitidos pelo canal do servidor e recebidos pelo canal cliente.

Para executar processamento adicional de mensagens no lado do cliente, você pode especificar uma implementação da IClientChannelSinkProvider qual todas as mensagens processadas pelo HttpClientChannel cliente são passadas.

Por padrão, o HttpServerChannel formato SOAP usa para serializar todas as mensagens.

Um HttpClientChannel objeto tem propriedades de configuração associadas que podem ser definidas em tempo de execução em um arquivo de configuração (invocando o método estático RemotingConfiguration.Configure ) ou programaticamente (passando uma IDictionary coleção para o HttpClientChannel construtor). Para obter uma lista dessas propriedades de configuração, consulte Propriedades de Configuração de Canal e Formatador.

Construtores

HttpClientChannel()

Inicializa uma nova instância da classe HttpClientChannel.

HttpClientChannel(IDictionary, IClientChannelSinkProvider)

Inicializa uma nova instância da classe HttpClientChannel com as propriedades de configuração e o coletor especificados.

HttpClientChannel(String, IClientChannelSinkProvider)

Inicializa uma nova instância da classe HttpClientChannel com o nome e o coletor especificados.

Campos

SinksWithProperties

Indica que o coletor de canal superior na pilha de coletores de canal.

(Herdado de BaseChannelWithProperties)

Propriedades

ChannelName

Obtém o nome do canal atual.

ChannelPriority

Obtém a prioridade do canal atual.

Count

Obtém o número de propriedades associadas ao objeto de canal.

(Herdado de BaseChannelObjectWithProperties)
IsFixedSize

Obtém um valor que indica se o número de propriedades que podem ser inseridas no canal de objeto é fixo.

(Herdado de BaseChannelObjectWithProperties)
IsReadOnly

Obtém um valor que indica se a coleção de propriedades no objeto de canal é somente leitura.

(Herdado de BaseChannelObjectWithProperties)
IsSecured

Obtém ou define se o canal do cliente é seguro.

IsSynchronized

Obtém um valor que indica se o dicionário de propriedades de objeto de canal é sincronizado.

(Herdado de BaseChannelObjectWithProperties)
Item[Object]

Retorna a propriedade de canal especificada.

Keys

Obtém um ICollection de chaves ao qual as propriedades do canal estão associadas.

Properties

Obtém um IDictionary das propriedades de canal associadas ao objeto de canal atual.

(Herdado de BaseChannelWithProperties)
SyncRoot

Obtém um objeto usado para sincronizar o acesso ao BaseChannelObjectWithProperties.

(Herdado de BaseChannelObjectWithProperties)
Values

Obtém um ICollection dos valores das propriedades associadas ao objeto de canal.

(Herdado de BaseChannelObjectWithProperties)

Métodos

Add(Object, Object)

Gera uma NotSupportedException.

(Herdado de BaseChannelObjectWithProperties)
Clear()

Gera uma NotSupportedException.

(Herdado de BaseChannelObjectWithProperties)
Contains(Object)

Retorna um valor que indica se o objeto de canal contém uma propriedade associada à chave especificada.

(Herdado de BaseChannelObjectWithProperties)
CopyTo(Array, Int32)

Gera uma NotSupportedException.

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

Retorna um coletor de mensagem de canal que entrega mensagens ao objeto de dados de URL ou de canal especificado.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetEnumerator()

Retorna um IDictionaryEnumerator que enumera em todas as propriedades associadas ao objeto de canal.

(Herdado de BaseChannelObjectWithProperties)
GetHashCode()

Serve como a função de hash padrão.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
Parse(String, String)

Extrai o URI do canal e o URI do objeto bem conhecido remoto da URL especificada.

Remove(Object)

Gera uma NotSupportedException.

(Herdado de BaseChannelObjectWithProperties)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Implantações explícitas de interface

IEnumerable.GetEnumerator()

Retorna um IEnumerator que enumera em todas as propriedades associadas ao objeto de canal.

(Herdado de BaseChannelObjectWithProperties)

Métodos de Extensão

Cast<TResult>(IEnumerable)

Converte os elementos de um IEnumerable para o tipo especificado.

OfType<TResult>(IEnumerable)

Filtra os elementos de um IEnumerable com base em um tipo especificado.

AsParallel(IEnumerable)

Habilita a paralelização de uma consulta.

AsQueryable(IEnumerable)

Converte um IEnumerable em um IQueryable.

Aplica-se a