Как создать экземпляр типа, активируемого клиентом
Этот раздел относится к технологии прежних версий, которая сохраняется для обеспечения обратной совместимости с существующими приложениями и не рекомендуется для разработки новых приложений. Сейчас распределенные приложения следует создавать с помощью Windows Communication Foundation (WCF).
В этом статье описаны два способа создания экземпляров объектов, активируемых клиентом. В первом случае используется метод CreateInstance, во втором — оператор new.
Создайте экземпляр с помощью метода Activator.CreateInstance
Создайте и зарегистрируйте объект TcpChannel
Dim channel As TcpChannel = New TcpChannel() ChannelServices.RegisterChannel(channel, False)
TcpChannel channel = new TcpChannel(); ChannelServices.RegisterChannel(channel, false);
Зарегистрируйте объект, активируемый клиентом
RemotingConfiguration.RegisterActivatedClientType( _ GetType(MyRemoteObject), _ "tcp://localhost:1234/MyServer")
RemotingConfiguration.RegisterActivatedClientType( typeof(MyRemoteObject), "tcp://localhost:1234/MyServer");
Вызовите метод CreateInstance
Dim url() As Object = {New UrlAttribute("tcp://localhost:1234/Server")} Dim obj As MyRemoteObject = CType(Activator.CreateInstance( _ GetType(MyRemoteObject), _ Nothing, _ url), MyRemoteObject)
object[] url = { new UrlAttribute("tcp://localhost:1234/Server") }; MyRemoteObject obj = (MyRemoteObject)Activator.CreateInstance( typeof(MyRemoteObject), null, url);
Создайте экземпляр с помощью оператора new.
Создайте и зарегистрируйте канал
Dim channel As TcpChannel = New TcpChannel() ChannelServices.RegisterChannel(channel, False)
TcpChannel channel = new TcpChannel(); ChannelServices.RegisterChannel(channel, false);
Зарегистрируйте объект, активируемый клиентом
RemotingConfiguration.RegisterActivatedClientType( _ GetType(MyRemoteObject), _ "tcp://localhost:1234/MyServer")
RemotingConfiguration.RegisterActivatedClientType( typeof(MyRemoteObject), "tcp://localhost:1234/MyServer");
Вызовите оператор new
Dim obj As MyRemoteObject = New MyRemoteObject(123)
MyRemoteObject obj = new MyRemoteObject(123);
Примеры
В следующем фрагменте кода показаны оба способа создания экземпляров, активируемых клиентом:
Imports System
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports System.Runtime.Remoting.Channels.Tcp
Imports System.Runtime.Remoting.Activation
Imports Server
Module Client
Sub Main()
' Create and register a channel
Dim channel As TcpChannel = New TcpChannel()
ChannelServices.RegisterChannel(channel, False)
' Register the client activated object
RemotingConfiguration.RegisterActivatedClientType( _
GetType(MyRemoteObject), _
"tcp://localhost:1234/MyServer")
' Call Activator.CreateInstance
Dim obj As MyRemoteObject = CType(Activator.CreateInstance( _
GetType(MyRemoteObject), _
Nothing, _
url), MyRemoteObject)
' OR call operator new
Dim obj As MyRemoteObject = New MyRemoteObject(123)
Console.WriteLine("Client.Main(): GetValue returned: {0}", obj.GetValue())
Console.WriteLine("Client.Main(): Calling SetValue(10)")
obj.SetValue(10)
Console.WriteLine("Client.Main(): GetValue returned: {0}", obj.GetValue())
End Sub
End Module
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Activation;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using Server;
namespace Client
{
class Client
{
static void Main(string[] args)
{
// Create and register channel
TcpChannel channel = new TcpChannel();
ChannelServices.RegisterChannel(channel, false);
// Register client activated object
RemotingConfiguration.RegisterActivatedClientType(
typeof(MyRemoteObject),
"tcp://localhost:1234/MyServer");
// Call Activator.CreateInstance
object[] url = { new UrlAttribute("tcp://localhost:1234/Server") };
MyRemoteObject obj = (MyRemoteObject)Activator.CreateInstance(
typeof(MyRemoteObject),
null,
url);
// OR call operator new
MyRemoteObject obj = new MyRemoteObject(123);
Console.WriteLine("Client.Main(): GetValue returned: " + obj.GetValue());
Console.WriteLine("Client.Main(): Calling SetValue(10)");
obj.SetValue(10);
Console.WriteLine("Client.Main(): GetValue returned: " + obj.GetValue());
}
}
}
Компиляция кода
Для этого примера требуются:
- ссылки на пространства имен System и System.Runtime.Remoting, а также пространство имен, реализующее MyRemoteObject.
См. также
Основные понятия
Активация удаленных объектов
Конфигурация удаленных приложений
Активация сервером
Аренда времени существования
Активация клиента
Дата сборки: 2010-02-13