HttpServerChannel Clase

Definición

Implementa un canal de servidor para llamadas remotas que utiliza el protocolo HTTP para transmitir los mensajes.

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
Herencia
Implementaciones

Ejemplos

En el ejemplo de código siguiente se muestra cómo usar un HttpServerChannel objeto para configurar un servidor de comunicación remota y su cliente. El ejemplo contiene tres partes:

  • Un servidor

  • Un cliente

  • Objeto remoto usado 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;

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.");
    }
}

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^ 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());
    }
}

En el ejemplo de código siguiente se muestra el objeto remoto usado por el servidor y el 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);
    }
}

Comentarios

Los canales transporten mensajes a través de límites de comunicación remota (por ejemplo, entre equipos en dominios de aplicación). La HttpServerChannel 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 se procesa. Los valores devueltos se transmiten por el canal de servidor y los recibe el canal de cliente.

Para realizar un procesamiento adicional de mensajes en el lado servidor, puede especificar una implementación de a través de la IServerChannelSinkProvider cual se pasan todos los mensajes procesados por .HttpServerChannel

HttpServerChannel acepta mensajes serializados en formato binario o SOAP.

Un HttpServerChannel 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 HttpServerChannel constructor). Para obtener una lista de estas propiedades de configuración, consulte la documentación de HttpServerChannel.

Constructores

HttpServerChannel()

Inicializa una nueva instancia de la clase HttpServerChannel.

HttpServerChannel(IDictionary, IServerChannelSinkProvider)

Inicializa una nueva instancia de la clase HttpServerChannel con las propiedades de canal y el receptor especificados.

HttpServerChannel(Int32)

Inicializa una nueva instancia de la clase HttpServerChannel que escucha en el puerto especificado.

HttpServerChannel(String, Int32)

Inicializa una nueva instancia de la clase HttpServerChannel con el nombre indicado y que realiza la escucha en el puerto especificado.

HttpServerChannel(String, Int32, IServerChannelSinkProvider)

Inicializa una nueva instancia de la clase HttpServerChannel en el puerto especificado con el nombre indicado, que realiza la escucha en el puerto especificado y utiliza el receptor 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)
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 IDictionary de las propiedades del canal asociadas con el objeto del canal actual.

(Heredado de BaseChannelWithProperties)
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 IChannelReceiverHook desea enlazarse al servicio del agente de escucha externo.

Métodos

Add(Object, Object)

Produce una excepción NotSupportedException.

(Heredado de BaseChannelObjectWithProperties)
AddHookChannelUri(String)

Agrega la dirección URI en la 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)
Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
GetChannelUri()

Devuelve la dirección URI del canal actual.

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