TcpChannel Clase

Definición

Proporciona una implementación de canal que utiliza el protocolo TCP para transmitir mensajes.

public ref class TcpChannel : System::Runtime::Remoting::Channels::IChannelReceiver, System::Runtime::Remoting::Channels::IChannelSender
public ref class TcpChannel : System::Runtime::Remoting::Channels::IChannelReceiver, System::Runtime::Remoting::Channels::IChannelSender, System::Runtime::Remoting::Channels::ISecurableChannel
public class TcpChannel : System.Runtime.Remoting.Channels.IChannelReceiver, System.Runtime.Remoting.Channels.IChannelSender
public class TcpChannel : System.Runtime.Remoting.Channels.IChannelReceiver, System.Runtime.Remoting.Channels.IChannelSender, System.Runtime.Remoting.Channels.ISecurableChannel
type TcpChannel = class
    interface IChannelReceiver
    interface IChannelSender
    interface IChannel
type TcpChannel = class
    interface IChannelReceiver
    interface IChannelSender
    interface IChannel
    interface ISecurableChannel
type TcpChannel = class
    interface IChannelReceiver
    interface IChannel
    interface IChannelSender
    interface ISecurableChannel
Public Class TcpChannel
Implements IChannelReceiver, IChannelSender
Public Class TcpChannel
Implements IChannelReceiver, IChannelSender, ISecurableChannel
Herencia
TcpChannel
Implementaciones

Ejemplos

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

En el ejemplo de código siguiente se muestra un servidor:

#using <System.Runtime.Remoting.dll>
#using <System.dll>
#using <common.dll>

using namespace System;
using namespace System::Runtime::Remoting;
using namespace System::Runtime::Remoting::Channels;
using namespace System::Runtime::Remoting::Channels::Tcp;
using namespace System::Security::Permissions;

[SecurityPermission(SecurityAction::Demand)]
int main(array<String^>^ args)
{
    // Create the server channel.
    TcpChannel^ serverChannel = gcnew TcpChannel(9090);

    // Register the server channel.
    ChannelServices::RegisterChannel(serverChannel);

    // Show the name of the channel.
    Console::WriteLine("The name of the channel is {0}.", 
        serverChannel->ChannelName);

    // Show the priority of the channel.
    Console::WriteLine("The priority of the channel is {0}.", 
        serverChannel->ChannelPriority);

    // Show the URIs associated with the channel.
    ChannelDataStore^ data = (ChannelDataStore^) serverChannel->ChannelData;
    for each (String^ uri in data->ChannelUris)
    {
        Console::WriteLine("The channel URI is {0}.", uri);
    }

    // Expose an object for remote calls.
    RemotingConfiguration::RegisterWellKnownServiceType(
        RemoteObject::typeid, "RemoteObject.rem", 
        WellKnownObjectMode::Singleton);

    // Parse the channel's URI.
    array<String^>^ urls = serverChannel->GetUrlsForUri("RemoteObject.rem");
    if (urls->Length > 0)
    {
        String^ objectUrl = urls[0];
        String^ objectUri;
        String^ channelUri = serverChannel->Parse(objectUrl, 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);
    }
        
    // Wait for the user prompt.
    Console::WriteLine("Press ENTER to exit the server.");
    Console::ReadLine();
}
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

public class Server
{
    public static void Main(string[] args)
    {
        // Create the server channel.
        TcpChannel serverChannel = new TcpChannel(9090);

        // Register the server channel.
        ChannelServices.RegisterChannel(serverChannel);

        // Show the name of the channel.
        Console.WriteLine("The name of the channel is {0}.",
            serverChannel.ChannelName);

        // Show the priority of the channel.
        Console.WriteLine("The priority of the channel is {0}.",
            serverChannel.ChannelPriority);

        // Show the URIs associated with the channel.
        ChannelDataStore data = (ChannelDataStore) serverChannel.ChannelData;
        foreach (string uri in data.ChannelUris)
        {
            Console.WriteLine("The channel URI is {0}.", uri);
        }

        // Expose an object for remote calls.
        RemotingConfiguration.RegisterWellKnownServiceType(
            typeof(RemoteObject), "RemoteObject.rem",
            WellKnownObjectMode.Singleton);

        // 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 URL is {0}.", objectUrl);
            Console.WriteLine("The object URI is {0}.", objectUri);
            Console.WriteLine("The channel URI is {0}.", channelUri);
        }

        // Wait for the user prompt.
        Console.WriteLine("Press ENTER to exit the server.");
        Console.ReadLine();
    }
}

En el ejemplo de código siguiente se muestra un cliente para este servidor:

#using <System.Runtime.Remoting.dll>
#using <System.dll>
#using <common.dll>

using namespace System;
using namespace System::Runtime::Remoting;
using namespace System::Runtime::Remoting::Channels;
using namespace System::Runtime::Remoting::Channels::Tcp;
using namespace System::Security::Permissions;

int main(array<String^>^ args)
{
    // Create the channel.
    TcpChannel^ clientChannel = gcnew TcpChannel();

    // Register the channel.
    ChannelServices::RegisterChannel(clientChannel, false);

    // Register as client for remote object.
    WellKnownClientTypeEntry^ remoteType = gcnew WellKnownClientTypeEntry(
        RemoteObject::typeid,"tcp://localhost:9090/RemoteObject.rem");
    RemotingConfiguration::RegisterWellKnownClientType(remoteType);

    // Create a message sink.
    String^ objectUri;
    System::Runtime::Remoting::Messaging::IMessageSink^ messageSink = 
        clientChannel->CreateMessageSink(
            "tcp://localhost:9090/RemoteObject.rem", nullptr,
            objectUri);
    Console::WriteLine("The URI of the message sink is {0}.", 
        objectUri);
    if (messageSink != nullptr)
    {
        Console::WriteLine("The type of the message sink is {0}.", 
            messageSink->GetType()->ToString());
    }

    // Create an instance of the remote object.
    RemoteObject^ service = gcnew 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());
}
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

public class Client
{
    public static void Main(string[] args)
    {
        // Create the channel.
        TcpChannel clientChannel = new TcpChannel();

        // Register the channel.
        ChannelServices.RegisterChannel(clientChannel, false);

        // Register as client for remote object.
        WellKnownClientTypeEntry remoteType = new WellKnownClientTypeEntry(
            typeof(RemoteObject),"tcp://localhost:9090/RemoteObject.rem");
        RemotingConfiguration.RegisterWellKnownClientType(remoteType);

        // Create a message sink.
        string objectUri;
        System.Runtime.Remoting.Messaging.IMessageSink messageSink =
            clientChannel.CreateMessageSink(
                "tcp://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());
        }

        // 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:
   int callCount;

public:
   RemoteObject()
      : callCount( 0 )
   {}

   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

Importante

Llamar a métodos de esta clase con datos que no son de confianza supone un riesgo de seguridad. Llame a los métodos de esta clase solo con datos de confianza. Para obtener más información, vea Validar todas las entradas.

Los canales transporten mensajes a través de límites de comunicación remota (por ejemplo, entre equipos en dominios de aplicación). La TcpChannel clase es una clase de conveniencia que combina la funcionalidad de la TcpClientChannel clase y la TcpServerChannel clase .

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, puede especificar implementaciones de y IServerChannelSinkProvider a través de IClientChannelSinkProvider las cuales se pasan todos los mensajes procesados por .TcpChannel

Un TcpChannel 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 TcpChannel constructor). Para obtener más información sobre las propiedades de configuración del canal, vea Propiedades de configuración de canal y formateador.

Constructores

TcpChannel()

Inicializa una nueva instancia de la clase TcpChannel activando únicamente un canal del cliente, y no un canal del servidor.

TcpChannel(IDictionary, IClientChannelSinkProvider, IServerChannelSinkProvider)

Inicializa una nueva instancia de la clase TcpChannel con las propiedades de configuración y receptores especificados.

TcpChannel(Int32)

Inicializa una nueva instancia de la clase TcpChannel con un canal de servidor que realiza la escucha en el puerto especificado.

Propiedades

ChannelData

Obtiene los datos específicos del canal.

ChannelName

Obtiene el nombre del canal actual.

ChannelPriority

Obtiene la prioridad del canal actual.

IsSecured

Obtiene o establece un valor booleano que indica si el canal actual es seguro.

Métodos

CreateMessageSink(String, Object, String)

Devuelve un receptor de mensajes de canal que envía mensajes a la dirección URL o al objeto de datos del canal especificados.

Equals(Object)

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

(Heredado de Object)
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 TcpChannel 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.

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)

Se aplica a