Coletores e cadeias coletor

Os clientes fazem chamadas de método em objetos remotos enviando mensagens para o domínio de aplicativo remoto. Isso é realizado por um conjunto de objetos do canal. O domínio de aplicativo do cliente contém um canal do cliente e o domínio de aplicativo remoto contém um canal remoto. Cada canal é composto de uma série de coletor de canal que são vinculados em uma cadeia. The seguinte illustration shows the estrutura of a Basic coletor de canal encadear.

Basic Channel Sink Chain

Basic Channel Chain Sink

Canais enviar cada mensagem junto uma cadeia de objetos do coletor de canal antes para enviar ou depois de receber uma mensagem. This cadeia de coletores contains sinks exigido FOR BASIC canalizar Functionality, such as formatador, transporte, or sinks stackbuilder, but you can personalizar the encadear coletor de canal to executar Especial Tasks with a mensagem or a transmitir. Cada recpetor de canal implementa ou IClientChannelSinkIServerChannelSinkhttps://msdn.microsoft.com/pt-br/library/t2695x5d(v=vs.85). O primeiro coletor de canal do cliente também deve implementar IMessageSinkhttps://msdn.microsoft.com/pt-br/library/c2k19cxd(v=vs.85). Ele geralmente implementa IClientFormatterSink (que herda Ambos IMessageSinkIChannelSinkBasee IClientChannelSink) e é chamado um coletor formatador porque ele transforma a de entrada mensagem em um transmitir (um objeto IMessagehttps://msdn.microsoft.com/pt-br/library/5c8cd72b(v=vs.85)).

The encadear coletor de canal Processos any mensagem that is sent to or from an domínio do aplicativo. Has a coletor de canal Acessar to the mensagem being Processed and processamento subsequent uses the mensagem that is returned to the sistema after processamento. This is a local natural to implementar a serviço log or any Classificar of filtro.

Each coletor de canal Processos the transmitir and then passes the transmitir to the próximo coletor de canal, which means that sinks before or after a specific coletor should know What to with the transmitir passed to them.

Dica

Coletores de mensagem não devem acionar exceções.One Way a coletor mensagem can controle this is by método quebra automática Código in try-Blocks capturar.

Channel coletor Providers (Objects that implementar the IClientChannelSinkProviderhttps://msdn.microsoft.com/pt-br/library/9y10763x(v=vs.85), IClientFormatterSinkProviderhttps://msdn.microsoft.com/pt-br/library/1cb0bd5b(v=vs.85), or interface IServerChannelSinkProvider) are responsible for Creating the canalizar that processo arquitetura de comunicação remota do.NET sinks Mensagens. When a remote type is activated, the channel sink provider is retrieved from the channel and the CreateSinkmethod is called on the sink provider to retrieve the first channel sink from the chain.

Coletor de canal é responsáveis por transporte de mensagens entre o cliente e o servidor. Coletor de canal é vinculados também em uma cadeia. When the CreateSinkmethod is called on a sink provider, it should do the following:

  • Criar a .

  • CALL CreateSink on the Avançar provedor coletor in the encadear.

  • Ensure that the Avançar coletor and the atual one are linked together.

  • Retornar seu coletor ao chamador.

Sinks Channel are responsible for Forwarding all Calls made on them to the Avançar coletor in the encadear and should Provide a Mechanism for Storing a reference to the Avançar coletor.

Coletor de canal tem grande flexibilidade na qual eles enviam para baixo da cadeia do coletor. De exemplo, pias de segurança que negociar autenticação antes de enviar o real serializado original mensagem pode conter até o completo mensagem canalizar, substituir o de conteúdo transmitir com seu próprios de conteúdo e enviá-lo para baixo a cadeia de coletores e para o Remoto domínio do aplicativo. On the viagem de retorno, the Segurança coletor can Intercept the mensagem de resposta, Creating a CONVERSATION with the correspondente Segurança sinks in the remoto domínio do aplicativo. Quando um contrato é atingido, o coletor de segurança de origem pode enviar o fluxo de conteúdo original em para o domínio de aplicativo remoto.

Mensagem de processamento no canal Coletor de corrente

Once the sistema de comunicação remota do.NET locates a canalizar that can Processo the mensagem, the canalizar passes the mensagem to the coletor de canal formatador by chamado SyncProcessMessage(IMessage) (or [M:System.Runtime.Remoting.Messaging.IMessageSink.AsyncProcessMessage(System.Runtime.Remoting.Messaging.IMessage, System.Runtime.Remoting.Messaging.IMessageSink)]https://msdn.microsoft.com/pt-br/library/6edcc4a2(v=vs.85)). The coletor formatador CREATES the matriz cabeçalho transporte and Calls [M:System.Runtime.Remoting.Channels.IClientChannelSink.GetRequestStream(System.Runtime.Remoting.Messaging.IMessage, System.Runtime.Remoting.Channels.ITransportHeaders)] on the Avançar coletor. Essa chamada é encaminhada para baixo da cadeia do coletor, e qualquer coletor pode criar um fluxo de Solicitar que é passado de volta para o coletor de formatador. Se [M:System.Runtime.Remoting.Channels.IClientChannelSink.GetRequestStream(System.Runtime.Remoting.Messaging.IMessage, System.Runtime.Remoting.Channels.ITransportHeaders)] retorna uma referência null (Nothing no Visual Basic), o coletor de formatador criará sua própria coletor a ser usado para a serialização. Depois que essa chamada retorna, a mensagem for serializada e a mensagem apropriada processamento método é chamada no coletor de canal primeiro na cadeia do coletor.

Coletores Não é possível gravar dados em fluxo de, mas pode ler a partir do fluxo ou passar um novo fluxo junto onde necessário. Sinks can also add headers to the header array (if they have not previously called [M:System.Runtime.Remoting.Channels.IClientChannelSink.GetRequestStream(System.Runtime.Remoting.Messaging.IMessage, System.Runtime.Remoting.Channels.ITransportHeaders)]on the next sink) and add themselves to the sink stack before forwarding the call to the next sink. (A pilha sincronizar é usada para permitir assíncrono chama para chamar voltar para o chamador quando elas estiverem concluído.) Quando a chamada alcançar o coletor de transporte ao final da cadeia, o coletor de transporte envia os cabeçalhos e serializado mensagem sobre o canal para o servidor onde o processo inteiro é revertido. The coletor de transporte (on the servidor) retrieves the Headers and serializado mensagem from the side of the transmitir servidor and forwards these Através the encadear coletor until the coletor formatador is reached. O coletor formatador desserializa a mensagem e Avançar-lo para o sistema de comunicação remota do.NET onde a mensagem está ativada voltar para chamar um método e é chamado no objeto de servidor.

Criar cadeias coletor do canal

Para criar um novo coletor de canal, você deve implementar e configurar o sistema de comunicação remota do.NET para reconhecer um IServerChannelSinkProvider ou IClientChannelSinkProvider implementação, que pode criar seu personalizado IClientChannelSinkIServerChannelSink implementação ou recuperar o Avançar coletor na encadear. You can use the classe abstrata BaseChannelSinkWithProperties to Ajuda implementar Your personalizado canalizar sinks.

Criando um provedor coletor do canal

Aplicativos podem fornecer Servidor ou provedores do coletor de canal do cliente como parâmetros ao construir um canal. Channel coletor providers should be stored in a encadear and it is the responsabilidade of the desenvolvedor to encadear Tudo coletor de canal providers together before the one OUTER to the construtor canalizar passing. Provedor de coletor de canal implementa uma propriedade Next para essa finalidade. The seguinte exemplo de código illustrates How to Compilação provedor de coletor de canal a cliente. A Concluir exemplo is disponível at Remoting Example: Canal provedor receptor.

private Function CreateDefaultClientProviderChain() As IClientChannelSinkProvider
   Dim chain As New FirstClientFormatterSinkProvider            
   Dim sink As IClientChannelSinkProvider
   sink = chain
   sink.Next = New SecondClientFormatterSinkProvider
   sink = sink.Next
   return chain
End Function 

private IClientChannelSinkProvider CreateDefaultClientProviderChain(){
   IClientChannelSinkProvider chain = new FirstClientFormatterSinkProvider();            
   IClientChannelSinkProvider sink = chain;
   sink.Next = new SecondClientFormatterSinkProvider();
   sink = sink.Next;
   return chain;
} 

Dica

When Múltiplo coletor de canal providers are provided in a arquivo de configuração, the sistema de comunicação remota do.NET Chains them together in the ordem in which they are found in the arquivo de configuração.Provedores de coletor de canal são criados quando o canal é criado durante a chamada Configure()https://msdn.microsoft.com/pt-br/library/ms223230(v=vs.85).

Coletores de formatador

Coletores de formatador serializar a mensagem de canal para o fluxo de mensagens como um objeto que implementa IMessage. Algumas implementações do coletor de formatador usam os tipos de formatador sistema-desde (BinaryFormatterhttps://msdn.microsoft.com/pt-br/library/y50tb888(v=vs.85) e SoapFormatterhttps://msdn.microsoft.com/pt-br/library/5ktza7xf(v=vs.85)). Outros implementações podem usar seus próprios meios para transformar a mensagem de canal para o fluxo.

A função do coletor de formatador é gerar os cabeçalhos necessários e serializar a mensagem para o fluxo. After the coletor formatador, the mensagem is forwarded to All sinks in the encadear coletor Através the SyncProcessMessage(IMessage) or Calls [M:System.Runtime.Remoting.Messaging.IMessageSink.AsyncProcessMessage(System.Runtime.Remoting.Messaging.IMessage, System.Runtime.Remoting.Messaging.IMessageSink)]https://msdn.microsoft.com/pt-br/library/6edcc4a2(v=vs.85). At this Stage the mensagem has already been serializado and cannot be Modificado.

Dica

Coletores que devem criar ou modificar a própria mensagem devem ser colocados na cadeia de coletor antes para o formatador.Isso é feito facilmente implementando IClientFormatterSink, assim, informando o sistema que ele tem uma referência para o coletor de formatador.O coletor de formatador real, em seguida, pode ser colocado mais adiante na cadeia do coletor.

On the viagem de retorno, the coletor formatador TRANSFORMS the transmitir mensagem Voltar into the objeto mensagem canalizar (return mensagem). O primeiro coletor no cliente deve implementar a interface IClientFormatterSink. When [M:System.Runtime.Remoting.Channels.IClientChannelSinkProvider.CreateSink(System.Runtime.Remoting.Channels.IChannelSender, System.String, System.Object)]returns to the channel, the reference returned is cast to an IClientFormatterSinktype so the SyncProcessMessage(IMessage)method can be called. Lembre-se de que é derivado IClientFormatterSinkIMessageSink. Se a conversão falhar, o sistema gera uma exceção.

Sinks Personalizar Channel

On the cliente, personalizado sinks canalizar are inserted em the encadear of Objects between the coletor formatador and the last coletor de transporte. Inserting a in the or Servidor enables you to the IMessage at one of the points:

  • Durante o processo pelo qual um chamar representado como uma mensagem é Convertido em um transmitir e enviado através de rede com fio.

  • During the process by which a stream is taken off the wire and sent to the StackBuilderSinkobject (the last message sink before the remote object on the server) or the proxy object (on the client).

Sinks Custom can ler or Gravar dados (depending if is the chamar de saída or de entrada) to the transmitir and adicionar informações Additional to the Headers WHERE desired. At this Stage, the mensagem has already been serializado by the formatador and cannot be Modificado. When the chamar mensagem is forwarded to the coletor de transporte at the end of the encadear, the coletor de transporte writes the Cabeçalhos to the transmitir and forwards the transmitir to the coletor de transporte on the servidor Using the protocolo transporte dictated by the canalizar.

Coletores de transporte

O coletor de transporte é o coletor último da cadeia no cliente e o primeiro coletor na cadeia no servidor. Além dos transportar a mensagem serializada, o coletor de transporte também é responsável por enviar os cabeçalhos para o servidor e recuperar os cabeçalhos e o fluxo quando a chamada retorna do servidor. These sinks are compilado em the canalizar and cannot be estendido.

Substituindo o formatador padrão

Como um canal é um mecanismo de rede abstrato, você pode configurar o sistema Remoting .NET para combinar um canal de sistema-implementado com qualquer formatador escolhido. Você pode fazer isso usando o construtor do canal que tem uma implementação IDictionary de propriedades do canal, um formatador no servidor e um formatador no cliente. Você também pode especificar o formatador em um arquivo de configuração. O exemplo a seguir instrui o sistema de configuração do sistema de interação remota .NET para criar um HttpChannel mas use o BinaryClientFormatterSink no cliente.

<configuration>
   <system.runtime.remoting>
      <application>
         <channels>
            <channel ref="http">
               <clientProviders>
                  <formatter ref="binary"/>
               </clientProviders>
         <channels>
      </application>
   </system.runtime.remoting>
</configuration> 

The following code does the same thing programmatically, assuming a remote interface type IServicethat implements GetServerString and GetServerTime:

Imports System
Imports System.Collections
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports System.Runtime.Remoting.Channels.Http

Public Class ClientProcess
  <MTAThread()> _
  Public Shared Sub Main()
      
    ' Note that any name/value pairs of configuration attributes can be 
    ' placed in this dictionary (the configuration system calls this same 
    ' constructor).
    Dim properties As New Hashtable()
    properties("name") = "HttpBinary"
     
    ChannelServices.RegisterChannel(New HttpChannel(properties, New BinaryClientFormatterSinkProvider(), Nothing))
    ' The last parameter above (Nothing) is the server sink provider chain 
    ' to obtain the default behavior (which includes SOAP and 
    ' binary formatters on the server side).
    Dim service As IService = CType(Activator.GetObject(GetType(IService), "http://computer:8080/SAService"), IService)
      
    Console.WriteLine("Server string is: " + service.GetServerString())
    Console.WriteLine("Server time is: " + service.GetServerTime())
  End Sub
   
End Class 

using System;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;

public class ClientProcess{

  public static void Main(string[] Args){
        
    // Note that any name/value pairs of configuration attributes can be 
    // placed in this dictionary (the configuration system calls this 
    // same HttpChannel constructor).
    IDictionary properties = new Hashtable();
    properties["name"] = "HttpBinary";

    // The last parameter below is the server sink provider chain 
    // to obtain the default behavior (which includes SOAP and binary 
    // formatters) on the server side.
    ChannelServices.RegisterChannel(new HttpChannel(properties, new BinaryClientFormatterSinkProvider(), null));

    IService service = (IService)Activator.GetObject(typeof(IService),"http://computer:8080/SAService");
        
    Console.WriteLine("Server string is: " + service.GetServerString());
    Console.WriteLine("Server time is: " + service.GetServerTime());      
  }
}

For a Concluir exemplo of this canalizar and Combination formatador Hosted in Serviços de Informações da Internet (IIS), see Example Remoting: Hosting in Information Internet Serviços (IIS).

To change this client to use a TcpChannel object with the SoapClientFormatterSinkhttps://msdn.microsoft.com/pt-br/library/cbethk1w(v=vs.85) object, you must change only the namespaces and the RegisterChannel(IChannel)call, as shown in the following code:

ChannelServices.RegisterChannel(New TcpChannel(properties, New SoapClientFormatterSinkProvider(), Nothing))

ChannelServices.RegisterChannel(new TcpChannel(properties, new SoapClientFormatterSinkProvider(), null));

Consulte também

Conceitos

Hosting Remoto Objects in Serviços de Informações da Internet (IIS)

Exemplo do Sistema de Interação Remota: Hosting in Information Internet Serviços (IIS)

Outros recursos

O sistema de interação remota avançado