Язык

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

Комментарии

Important

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

Каналы транспорта сообщений через границы удаленного взаимодействия (например, между компьютерами в доменах приложений). Класс 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)

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