Compartilhar via


HttpChannel Classe

Definição

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

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
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 dessa classe com dados não confiáveis é um risco à segurança. Chame os métodos dessa classe apenas com 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 HttpChannel classe transporta mensagens usando o protocolo HTTP.

Os canais são usados pela infraestrutura de comunicação remota do .NET Framework para transportar chamadas remotas. Quando um cliente faz uma chamada para um objeto remoto, a chamada é serializada em uma mensagem que é 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 do cliente.

Um HttpChannel 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 HttpChannel construtor).

Construtores

Nome Description
HttpChannel()

Inicializa uma nova instância da classe HttpChannel.

HttpChannel(IDictionary, IClientChannelSinkProvider, IServerChannelSinkProvider)

Inicializa uma nova instância da HttpChannel classe com as propriedades de configuração e os coletores especificados.

HttpChannel(Int32)

Inicializa uma nova instância da HttpChannel classe com um canal de servidor que escuta na porta especificada.

Campos

Nome Description
SinksWithProperties

Indica o coletor de canal superior na pilha do coletor do canal.

(Herdado de BaseChannelWithProperties)

Propriedades

Nome Description
ChannelData

Obtém os dados específicos do canal.

ChannelName

Obtém o nome do canal atual.

ChannelPriority

Obtém a prioridade do canal atual.

ChannelScheme

Obtém o tipo de ouvinte para conectar (por exemplo, "http").

ChannelSinkChain

Obtém a cadeia de coletores de canal que o canal atual está usando.

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 objeto de canal é 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 um valor booliano que indica se o canal atual é 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 uma ICollection das chaves às quais as propriedades do canal estão associadas.

Properties

Obtém uma IDictionary das propriedades do canal associadas ao canal atual.

SyncRoot

Obtém um objeto usado para sincronizar o BaseChannelObjectWithPropertiesacesso ao .

(Herdado de BaseChannelObjectWithProperties)
Values

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

(Herdado de BaseChannelObjectWithProperties)
WantsToListen

Obtém um valor booliano que indica se a instância atual deseja ser conectada ao serviço de ouvinte externo.

Métodos

Nome Description
Add(Object, Object)

Lança NotSupportedException.

(Herdado de BaseChannelObjectWithProperties)
AddHookChannelUri(String)

Adiciona um URI no qual o gancho de canal deve escutar.

Clear()

Lança 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)

Lança NotSupportedException.

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

Retorna um coletor de mensagens de canal que fornece mensagens para a URL especificada ou objeto de dados de canal.

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)
GetUrlsForUri(String)

Retorna uma matriz de todas as URLs de um objeto com o URI especificado, hospedado no atual HttpChannel.

MemberwiseClone()

Cria uma cópia superficial do Objectatual.

(Herdado de Object)
Parse(String, String)

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

Remove(Object)

Lança NotSupportedException.

(Herdado de BaseChannelObjectWithProperties)
StartListening(Object)

Instrui o canal atual a começar a escutar solicitações.

StopListening(Object)

Instrui o canal atual a parar de escutar solicitações.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Implantações explícitas de interface

Nome Description
IEnumerable.GetEnumerator()

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

(Herdado de BaseChannelObjectWithProperties)

Métodos de Extensão

Nome Description
AsParallel(IEnumerable)

Habilita a paralelização de uma consulta.

AsQueryable(IEnumerable)

Converte um IEnumerable em um IQueryable.

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.

Aplica-se a