HttpServerChannel Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Implementa um canal servidor para chamadas remotas que utiliza o protocolo HTTP para transmitir mensagens.
public ref class HttpServerChannel : System::Runtime::Remoting::Channels::BaseChannelWithProperties, System::Runtime::Remoting::Channels::IChannelReceiver, System::Runtime::Remoting::Channels::IChannelReceiverHook
public class HttpServerChannel : System.Runtime.Remoting.Channels.BaseChannelWithProperties, System.Runtime.Remoting.Channels.IChannelReceiver, System.Runtime.Remoting.Channels.IChannelReceiverHook
type HttpServerChannel = class
inherit BaseChannelWithProperties
interface IChannelReceiver
interface IChannel
interface IChannelReceiverHook
Public Class HttpServerChannel
Inherits BaseChannelWithProperties
Implements IChannelReceiver, IChannelReceiverHook
- Herança
- Implementações
Exemplos
O exemplo de código seguinte mostra como usar um HttpServerChannel objeto para configurar um servidor remoto e o seu cliente. O exemplo contém três partes:
Um servidor
Um cliente
Um objeto remoto usado pelo servidor e pelo cliente
O seguinte exemplo de código 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;
int main()
{
// Create the server channel.
HttpServerChannel^ serverChannel = gcnew HttpServerChannel( 9090 );
// Register the server channel.
ChannelServices::RegisterChannel( serverChannel );
// Display the channel's scheme.
Console::WriteLine( L"The channel scheme is {0}.", serverChannel->ChannelScheme );
// Display the channel's URI.
Console::WriteLine( L"The channel URI is {0}.", serverChannel->GetChannelUri() );
// Expose an object for remote calls.
RemotingConfiguration::RegisterWellKnownServiceType(
RemoteObject::typeid, L"RemoteObject.rem", WellKnownObjectMode::Singleton );
// Get the channel's sink chain.
IServerChannelSink^ sinkChain = serverChannel->ChannelSinkChain;
Console::WriteLine( L"The type of the server channel's sink chain is {0}.", sinkChain->GetType() );
// See if the channel wants to listen.
bool wantsToListen = serverChannel->WantsToListen;
Console::WriteLine( L"The value of WantsToListen is {0}.", wantsToListen );
// Parse the channel's URI.
array<String^>^ urls = serverChannel->GetUrlsForUri( L"RemoteObject.rem" );
if ( urls->Length > 0 )
{
String^ objectUrl = urls[ 0 ];
String^ objectUri;
String^ channelUri = serverChannel->Parse( objectUrl, objectUri );
Console::WriteLine( L"The object URI is {0}.", objectUri );
Console::WriteLine( L"The channel URI is {0}.", channelUri );
Console::WriteLine( L"The object URL is {0}.", objectUrl );
}
// 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);
// Display the channel's scheme.
Console.WriteLine("The channel scheme is {0}.",
serverChannel.ChannelScheme);
// Display the channel's URI.
Console.WriteLine("The channel URI is {0}.",
serverChannel.GetChannelUri());
// Expose an object for remote calls.
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(RemoteObject), "RemoteObject.rem",
WellKnownObjectMode.Singleton);
// Get the channel's sink chain.
IServerChannelSink sinkChain = serverChannel.ChannelSinkChain;
Console.WriteLine(
"The type of the server channel's sink chain is {0}.",
sinkChain.GetType().ToString());
// See if the channel wants to listen.
bool wantsToListen = serverChannel.WantsToListen;
Console.WriteLine(
"The value of WantsToListen is {0}.",
wantsToListen);
// Parse the channel's URI.
string[] urls = serverChannel.GetUrlsForUri("RemoteObject.rem");
if (urls.Length > 0)
{
string objectUrl = urls[0];
string objectUri;
string channelUri =
serverChannel.Parse(objectUrl, out objectUri);
Console.WriteLine("The object URI is {0}.", objectUri);
Console.WriteLine("The channel URI is {0}.", channelUri);
Console.WriteLine("The object URL is {0}.", objectUrl);
}
// Wait for the user prompt.
Console.WriteLine("Press ENTER to exit the server.");
Console.ReadLine();
Console.WriteLine("The server is exiting.");
}
}
O seguinte exemplo de código 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^ channel = gcnew HttpClientChannel;
// Register the channel.
ChannelServices::RegisterChannel( channel );
// Register as client for remote object.
WellKnownClientTypeEntry^ remoteType = gcnew WellKnownClientTypeEntry(
RemoteObject::typeid,L"http://localhost:9090/RemoteObject.rem" );
RemotingConfiguration::RegisterWellKnownClientType( remoteType );
// 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 channel = new HttpClientChannel();
// Register the channel.
ChannelServices.RegisterChannel(channel);
// Register as client for remote object.
WellKnownClientTypeEntry remoteType = new WellKnownClientTypeEntry(
typeof(RemoteObject),"http://localhost:9090/RemoteObject.rem");
RemotingConfiguration.RegisterWellKnownClientType(remoteType);
// 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 seguinte mostra o objeto remoto usado pelo servidor e pelo cliente.
using namespace System;
using namespace System::Runtime::Remoting;
// Remote object.
public ref class RemoteObject: public MarshalByRefObject
{
private:
static int callCount = 0;
public:
int GetCount()
{
callCount++;
return (callCount);
}
};
using System;
using System.Runtime.Remoting;
// Remote object.
public class RemoteObject : MarshalByRefObject
{
private int callCount = 0;
public int GetCount()
{
callCount++;
return(callCount);
}
}
Observações
Os canais transportam mensagens através de fronteiras remotas (por exemplo, entre computadores em domínios de aplicação). A HttpServerChannel classe transporta mensagens usando o protocolo HTTP.
Os canais são usados pela infraestrutura remota do .NET Framework para transportar chamadas remotas. Quando um cliente faz uma chamada para um objeto remoto, a chamada é serializada numa mensagem enviada por um canal cliente e recebida por um canal servidor. Depois, é desserializado e processado. Quaisquer valores devolvidos são transmitidos pelo canal do servidor e recebidos pelo canal cliente.
Para realizar um processamento adicional de mensagens do lado do servidor, pode especificar uma implementação do IServerChannelSinkProvider através da qual todas as mensagens processadas pelo HttpServerChannel são passadas.
Aceita HttpServerChannel mensagens serializadas em formato binário ou SOAP.
Um HttpServerChannel objeto tem propriedades de configuração associadas que podem ser definidas em tempo de execução, seja num ficheiro de configuração (invocando o método estático RemotingConfiguration.Configure ) ou programaticamente (passando uma IDictionary coleção ao HttpServerChannel construtor). Para uma lista destas propriedades de configuração, consulte a documentação para HttpServerChannel.
Construtores
| Name | Description |
|---|---|
| HttpServerChannel() |
Inicializa uma nova instância da HttpServerChannel classe. |
| HttpServerChannel(IDictionary, IServerChannelSinkProvider) |
Inicializa uma nova instância da HttpServerChannel classe com as propriedades do canal e o sumidouro especificados. |
| HttpServerChannel(Int32) |
Inicializa uma nova instância da HttpServerChannel classe que escuta na porta especificada. |
| HttpServerChannel(String, Int32, IServerChannelSinkProvider) |
Inicializa uma nova instância da HttpServerChannel classe na porta especificada com o nome próprio, que ouve na porta especificada e utiliza o sumidouro especificado. |
| HttpServerChannel(String, Int32) |
Inicializa uma nova instância da HttpServerChannel classe com o nome próprio e que escuta na porta especificada. |
Campos
| Name | Description |
|---|---|
| SinksWithProperties |
Indica o sumidouro superior do canal na pilha do sumidouro do canal. (Herdado de BaseChannelWithProperties) |
Propriedades
| Name | Description |
|---|---|
| ChannelData |
Obtém dados específicos do canal. |
| ChannelName |
Recebe o nome do canal atual. |
| ChannelPriority |
Recebe a prioridade do canal atual. |
| ChannelScheme |
Obtém o tipo de ouvinte para se ligar (por exemplo, "http"). |
| ChannelSinkChain |
Obtém a cadeia de dissipação de canal que o canal atual está a usar. |
| Count |
Obtém o número de propriedades associadas ao objeto do canal. (Herdado de BaseChannelObjectWithProperties) |
| IsFixedSize |
Obtém um valor que indica se o número de propriedades que podem ser introduzidas no objeto de canal é fixo. (Herdado de BaseChannelObjectWithProperties) |
| IsReadOnly |
Recebe um valor que indica se a coleção de propriedades no objeto canal é apenas de leitura. (Herdado de BaseChannelObjectWithProperties) |
| IsSynchronized |
Obtém um valor que indica se o dicionário das propriedades do objeto do canal está sincronizado. (Herdado de BaseChannelObjectWithProperties) |
| Item[Object] |
Devolve a propriedade de canal especificada. |
| Keys |
Obtém uma ICollection de chaves com as propriedades do canal associadas. |
| Properties |
Obtém uma IDictionary das propriedades do canal associadas ao objeto de canal atual. (Herdado de BaseChannelWithProperties) |
| SyncRoot |
Obtém um objeto que é usado para sincronizar o acesso ao BaseChannelObjectWithProperties. (Herdado de BaseChannelObjectWithProperties) |
| Values |
Obtém um ICollection dos valores das propriedades associadas ao objeto do canal. (Herdado de BaseChannelObjectWithProperties) |
| WantsToListen |
Recebe um valor booleano que indica se IChannelReceiverHook quer ser ligado ao serviço de ouvinte externo. |
Métodos
| Name | Description |
|---|---|
| Add(Object, Object) |
Lança um NotSupportedException. (Herdado de BaseChannelObjectWithProperties) |
| AddHookChannelUri(String) |
Adiciona um URI onde o gancho do canal deve ouvir. |
| Clear() |
Lança um NotSupportedException. (Herdado de BaseChannelObjectWithProperties) |
| Contains(Object) |
Devolve um valor que indica se o objeto canal contém uma propriedade associada à chave especificada. (Herdado de BaseChannelObjectWithProperties) |
| CopyTo(Array, Int32) |
Lança um NotSupportedException. (Herdado de BaseChannelObjectWithProperties) |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetChannelUri() |
Devolve o URI do canal atual. |
| GetEnumerator() |
Devolve a IDictionaryEnumerator que enumera sobre todas as propriedades associadas ao objeto canal. (Herdado de BaseChannelObjectWithProperties) |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| GetUrlsForUri(String) |
Devolve um array de todas as URLs de um objeto com o URI especificado, alojado no arquivo atual HttpChannel. |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| Parse(String, String) |
Extrai o URI do canal e o URI remoto do objeto conhecido a partir da URL especificada. |
| Remove(Object) |
Lança um NotSupportedException. (Herdado de BaseChannelObjectWithProperties) |
| StartListening(Object) |
Instrui o canal atual a começar a ouvir pedidos. |
| StopListening(Object) |
Instrui o canal atual a parar de ouvir pedidos. |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |
Implementações de Interface Explícita
| Name | Description |
|---|---|
| IEnumerable.GetEnumerator() |
Devolve a IEnumerator que enumera sobre todas as propriedades associadas ao objeto do canal. (Herdado de BaseChannelObjectWithProperties) |
Métodos da Extensão
| Name | Description |
|---|---|
| AsParallel(IEnumerable) |
Permite a paralelização de uma consulta. |
| AsQueryable(IEnumerable) |
Converte um IEnumerable para um IQueryable. |
| Cast<TResult>(IEnumerable) |
Conjura os elementos de an IEnumerable para o tipo especificado. |
| OfType<TResult>(IEnumerable) |
Filtra os elementos de um IEnumerable com base num tipo especificado. |