IpcChannel Класс

Определение

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

public ref class IpcChannel : System::Runtime::Remoting::Channels::IChannelReceiver, System::Runtime::Remoting::Channels::IChannelSender, System::Runtime::Remoting::Channels::ISecurableChannel
public class IpcChannel : System.Runtime.Remoting.Channels.IChannelReceiver, System.Runtime.Remoting.Channels.IChannelSender, System.Runtime.Remoting.Channels.ISecurableChannel
type IpcChannel = class
    interface IChannelReceiver
    interface IChannelSender
    interface IChannel
    interface ISecurableChannel
type IpcChannel = class
    interface IChannelReceiver
    interface IChannel
    interface IChannelSender
    interface ISecurableChannel
Public Class IpcChannel
Implements IChannelReceiver, IChannelSender, ISecurableChannel
Наследование
IpcChannel
Реализации

Примеры

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

  • Сервер

  • Клиент

  • Удаленный объект, используемый сервером и клиентом.

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

#using <System.dll>
#using <System.Runtime.Remoting.dll>
#using "common.dll"
using namespace System;
using namespace System::Runtime::Remoting::Channels::Ipc;

void main()
{
   // Create the server channel.
   IpcChannel^ serverChannel = gcnew IpcChannel( L"localhost:9090" );

   // Register the server channel.
   System::Runtime::Remoting::Channels::ChannelServices::RegisterChannel( serverChannel );

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

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

   // Show the URIs associated with the channel.
   System::Runtime::Remoting::Channels::ChannelDataStore^ channelData = (System::Runtime::Remoting::Channels::ChannelDataStore^)serverChannel->ChannelData;
   for each (String^ uri in channelData->ChannelUris)
   {
      Console::WriteLine("The channel URI is {0}.", uri);
   }
   
   // Expose an object for remote calls.
   System::Runtime::Remoting::RemotingConfiguration::RegisterWellKnownServiceType(
         RemoteObject::typeid,L"RemoteObject.rem",
         System::Runtime::Remoting::WellKnownObjectMode::Singleton);
   
   // 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.Channels.Ipc;

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

        // Register the server channel.
        System.Runtime.Remoting.Channels.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.
        System.Runtime.Remoting.Channels.ChannelDataStore channelData =
            (System.Runtime.Remoting.Channels.ChannelDataStore)
            serverChannel.ChannelData;
        foreach (string uri in channelData.ChannelUris)
        {
            Console.WriteLine("The channel URI is {0}.", uri);
        }

        // Expose an object for remote calls.
        System.Runtime.Remoting.RemotingConfiguration.
            RegisterWellKnownServiceType(
                typeof(RemoteObject), "RemoteObject.rem",
                System.Runtime.Remoting.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 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.");
    }
}

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

#using <System.dll>
#using <System.Runtime.Remoting.dll>
#using "common.dll"
using namespace System;
using namespace System::Runtime::Remoting::Channels::Ipc;

void main()
{
   
   // Create the channel.
   IpcChannel^ channel = gcnew IpcChannel;
   
   // Register the channel.
   System::Runtime::Remoting::Channels::ChannelServices::RegisterChannel(channel);
   
   // Register as client for remote object.
   System::Runtime::Remoting::WellKnownClientTypeEntry^ remoteType = gcnew
       System::Runtime::Remoting::WellKnownClientTypeEntry( 
         RemoteObject::typeid,L"ipc://localhost:9090/RemoteObject.rem" );
   System::Runtime::Remoting::RemotingConfiguration::RegisterWellKnownClientType(remoteType);
   
   // Create a message sink.
   String^ objectUri;
   System::Runtime::Remoting::Messaging::IMessageSink^ messageSink = channel->CreateMessageSink(
      L"ipc://localhost:9090/RemoteObject.rem", nullptr, objectUri );
   Console::WriteLine( L"The URI of the message sink is {0}.", objectUri );
   if ( messageSink != nullptr )
   {
      Console::WriteLine( L"The type of the message sink is {0}.", messageSink->GetType() );
   }

   
   // 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.Channels.Ipc;

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

        // Register the channel.
        System.Runtime.Remoting.Channels.ChannelServices.
            RegisterChannel(channel);

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

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

// Remote object.
public ref class RemoteObject: public MarshalByRefObject
{
private:
   static int callCount = 0;

public:
   int GetCount()
   {
      Console::WriteLine( L"GetCount has been called." );
      callCount++;
      return (callCount);
   }

};
using System;

// Remote object.
public class RemoteObject : MarshalByRefObject
{
    private int callCount = 0;

    public int GetCount()
    {
        Console.WriteLine("GetCount has been called.");
        callCount++;
        return(callCount);
    }
}

Комментарии

Важно!

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

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

Класс IpcChannel — это удобный класс, объединяющий функциональные IpcClientChannel возможности класса и IpcServerChannel класса .

Внимание!

При задании свойству exclusiveAddressUse значения false в аргументе properties можно зарегистрировать несколько IpcServerChannel объектов для одного именованного канала. В этом случае запросы могут отправляться в любой из зарегистрированных каналов. Этот параметр считается безопасным, только в том случае, если используются ALC.

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

IpcChannel()

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

IpcChannel(IDictionary, IClientChannelSinkProvider, IServerChannelSinkProvider)

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

IpcChannel(IDictionary, IClientChannelSinkProvider, IServerChannelSinkProvider, CommonSecurityDescriptor)

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

IpcChannel(String)

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

Свойства

ChannelData

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

ChannelName

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

ChannelPriority

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

IsSecured

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

Методы

CreateMessageSink(String, Object, String)

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

Equals(Object)

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

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

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

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

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

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

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

MemberwiseClone()

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

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

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

StartListening(Object)

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

StopListening(Object)

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

ToString()

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

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

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