TcpChannel Класс

Определение

Обеспечивает реализацию канала, в котором для передачи сообщений используется протокол TCP.

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
Наследование
TcpChannel
Реализации

Примеры

В следующем примере кода показано, как использовать TcpChannel для настройки сервера удаленного взаимодействия и его клиента. Пример содержит три части: сервер, клиент и удаленный объект, используемый сервером и клиентом.

В следующем примере кода показан сервер:

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

В следующем примере кода показан клиент для этого сервера:

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

В следующем примере кода показан удаленный объект, используемый сервером и клиентом:

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

Комментарии

Важно!

Вызов методов этого класса для ненадежных данных представляет угрозу безопасности. Вызывайте методы класса только для надежных данных. Дополнительные сведения см. в разделе Проверка всех входных данных.

Каналы передают сообщения через границы удаленного взаимодействия (например, между компьютерами в доменах приложений). Класс TcpChannel — это удобный класс, объединяющий функциональные TcpClientChannel возможности класса и TcpServerChannel класса .

Каналы используются инфраструктурой удаленного взаимодействия платформа .NET Framework для передачи удаленных вызовов. Когда клиент выполняет вызов удаленного объекта, вызов сериализуется в сообщение, которое отправляется клиентским каналом и принимается каналом сервера. Затем он десериализируется и обрабатывается. Все возвращаемые значения передаются каналом сервера и принимаются клиентским каналом.

Чтобы выполнить дополнительную обработку сообщений, можно указать реализации IClientChannelSinkProvider и IServerChannelSinkProvider , через которые передаются все сообщения, обработанные TcpChannel .

Объект TcpChannel имеет связанные свойства конфигурации, которые можно задать во время выполнения в файле конфигурации (путем вызова статического RemotingConfiguration.Configure метода) или программно (путем передачи IDictionary коллекции конструктору TcpChannel ). Дополнительные сведения о свойствах конфигурации канала см. в разделе Свойства конфигурации канала и модуля форматирования.

Конструкторы

TcpChannel()

Инициализирует новый экземпляр класса TcpChannel, активируя только клиентский, но не серверный канал.

TcpChannel(IDictionary, IClientChannelSinkProvider, IServerChannelSinkProvider)

Инициализирует новый экземпляр класса TcpChannel с указанными свойствами конфигурации и приемником.

TcpChannel(Int32)

Инициализирует новый экземпляр класса TcpChannel с каналом сервера, который ожидает передачу данных для указанного порта межпроцессного взаимодействия.

Свойства

ChannelData

Получает данные для указанного канала.

ChannelName

Получает имя текущего канала.

ChannelPriority

Получает приоритет текущего канала.

IsSecured

Возвращает или задает логическое значение, позволяющее определить, является ли текущий канал безопасным.

Методы

CreateMessageSink(String, Object, String)

Возвращает приемник сообщений канала, который доставляет сообщения объекту данных канала или по указанному URL-адресу.

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
GetUrlsForUri(String)

Возвращает массив всех URL-адресов объекта с указанным универсальным кодом ресурса (URI), относящихся к текущему объекту TcpChannel.

MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
Parse(String, String)

Выделяет универсальный код ресурса (URI) канала и универсальный код ресурса (URI) известного удаленного объекта из указанного URL-адреса.

StartListening(Object)

Дает текущему каналу команду на отслеживание запросов.

StopListening(Object)

Дает текущему каналу команду на прекращение отслеживания запросов.

ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Применяется к