Remoting programming Knowledge A

Source: Internet
Author: User
Tags config constructor datetime readline
Programming Remoting Basics


Basic principle
When a client creates an instance of a remote Remotableclass,. NET Framework generates a proxy in the client application domain. The agent looks like an actual object. After the agent receives the call, it connects to the remote object through the channel.



First, the preparation of steps

First step


Write a DLL that contains the classes you want to remottable

public class Remotableclass:marshalbyrefobject

{

....

}




Second Step

The server process registers the remotable class so that other applications can be activated. Depending on how the object is activated, the server is registered by two static methods: Registeractivatedservicetype or RegisterWellKnownServiceType. The following statement uses RegisterWellKnownServiceType to register the remotableclass for remote activation.

RemotingConfiguration.RegisterWellKnownServiceType (

Typeof (Remotableclass),//remotable class

URI of "RemoteObject",//Remotable class

WellKnownObjectMode.SingleCall); Activation mode

The first parameter refers to a class that can be remotely typed.

The second refers to the URI that the client uses to activate the object----that is, the client tells the server to activate

The URI of the Remotableclass instance.

The third parameter specifies the activation mode. There are two options. WellKnownObjectMode.SingleCall is the creation of a new instance for each call to a client. Wellknownobjectmode.singleton refers to the creation of a Remotableclass instance to handle the invocation of all clients.

Third Step

In order for the client to use Remotableclass, the server process must be created to register a channel. This channel provides a channel for object and remote client communication. On the server side,. NET Framework provides two types of channels:

System.Runtime.Remoting.Channels.Tcp.TcpServerChannel: Can accept TCP connections from remote clients.

System.Runtime.Remoting.Channels.Http.HttpServerChannel: Accept Http connections.

The following statement creates a TcpServerChannel channel that is listening on port 1234 and uses the. NET Framework Registration:

TcpServerChannel channel = new TcpServerChannel (1234);

ChannelServices.RegisterChannel (channel);

The following statement registers an HTTP channel that is listening on port 1234:

Httpservicechannel channel = new HttpServerChannel (1234);

ChannelServices.RegisterChannel (channel);

TcpServerChannel is more efficient. HttpServerChannel is the choice that is used when using IIS as a remote Activation agent.


Fourth Step

In order to create an instance of a remote class, the client must also do some registration.

First, you must register a client channel. NET Framework provides two types of client channels: TcpClientChannel and HttpClientChannel, which correspond to the server-side channel respectively.

Second, if the client wants to use the new operator to produce the remote object, the remote object must be registered to the local application domain.

Remotingconfiguration.registerwellknownclienttype is registering a class on the client.

RemotingConfiguration.RegisterWellKnownServiceType is registering a class on the server.

The following code registers a TCP channel with the client and also registers the Remotableclass in the local application domain:

TcpClientChannel channel = new TcpClientChannel ();

ChannelServices.RegisterChannel (channel);



Remotingconfiguration.registerwellknownclienttype (

Typeof (Remotableclass),

"Tcp://localhost:1234/remoteobject");

The second parameter refers to the URL of the remote object.

The protocol must match the channel protocol registered by the application.

You can replace localhost with a machine name or an IP address.

The number of ports must be as good as the number of ports on the server side.

Object URI, which must match the server with the RegisterWellKnownServiceType registration.

Fifth Step

To generate an agent using new on the client:

Remotableclass rc = new Remotableclass ();

This operation generates a proxy in the client application domain and returns a reference to Remotableclass.

Ii. Practical examples

ClockServer.cs

Using System;
public class Clock:marshalbyrefobject
{
public string GetCurrentTime ()
{
return DateTime.Now.ToLongTimeString ();
}
}
TimeServer.cs

Using System;
Using System.Runtime.Remoting;
Using System.Runtime.Remoting.Channels;
Using SYSTEM.RUNTIME.REMOTING.CHANNELS.TCP;
Class MYAPP
{
static void Main ()
{
TcpServerChannel channel = new TcpServerChannel (1234);
ChannelServices.RegisterChannel (channel);

RemotingConfiguration.RegisterWellKnownServiceType
(typeof (Clock), "Clock", WellKnownObjectMode.SingleCall);

Console.WriteLine ("Press Enter to terminate ...");
Console.ReadLine ();
}
}
TimeClient.cs

Using System;
Using System.Runtime.Remoting;
Using System.Runtime.Remoting.Channels;
Using SYSTEM.RUNTIME.REMOTING.CHANNELS.TCP;
Class MYAPP
{
static void Main ()
{
TcpClientChannel channel = new TcpClientChannel ();
ChannelServices.RegisterChannel (channel);

Remotingconfiguration.registerwellknownclienttype
(typeof (Clock), "Tcp://localhost:1234/clock");
Clock Clock = new Clock ();
Console.WriteLine (Clock. GetCurrentTime ());
}
}
Compile:

1. Csc/t:library Clockserver.cs
2. Csc/r:clockserver.dll Timeserver.cs
3. Csc/r:clockserver.dll Timeclient.cs
To copy the ClockServer.dll to the client. When the proxy for the remote object is created. NET Framework needs to describe the original data of the clock class. It can get the original data from the DLL.



Third, the configuration mode

Timeserver and Timeclient register channels and remote classes within their source code. This has a disadvantage, once any registration data changes, you have to modify the source code, and recompile.

That's why. NET Framework supports another form of registration. Declaring registration is by calling a static

RemotingConfiguration.Configure method to get information from the config file.

Examples are as follows:

ClockServer.cs

Using System;

public class Clock:marshalbyrefobject
{
public string GetCurrentTime ()
{
return DateTime.Now.ToLongTimeString ();
}
}

TimeServer.cs

Using System;
Using System.Runtime.Remoting;

Class MYAPP
{
static void Main ()
{
RemotingConfiguration.Configure ("TimeServer.exe.config");
Console.WriteLine ("Press Enter to terminate ...");
Console.ReadLine ();
}
}
TimeServer.exe.config

<configuration>
<system.runtime.remoting>
<application>
<service>
<wellknown mode= "SingleCall" type= "Clock, Clockserver"
objecturi= "Clock"/>
</service>
<channels>
<channel ref= "TCP Server" port= "1234"/>
</channels>
</application>
</system.runtime.remoting>
</configuration>
TimeClient.cs

Using System;
Using System.Runtime.Remoting;

Class MYAPP
{
static void Main ()
{
RemotingConfiguration.Configure ("TimeClient.exe.config");
Clock Clock = new Clock ();
Console.WriteLine (Clock. GetCurrentTime ());
}
}
TimeClient.exe.config

<configuration>
<system.runtime.remoting>
<application>
<client>
<wellknown type= "Clock, Clockserver"
Url= "Tcp://localhost:1234/clock"/>
</client>
<channels>
<channel ref= "TCP Client"/>
</channels>
</application>
</system.runtime.remoting>
</configuration>
The disadvantage of this approach is that the configuration file can be modified and deleted.


Iv. Mode of activation

. NET Framework divides remotable objects into two types: server-activated objects and client-activated objects. Server-side activation objects are passed through RemotingConfiguration ' Sregisterwellknownservicetype and

The Registerwellknownclienttype method is registered. The example above is a server-side activation object. Client-activated objects are registered through Registeractivateservicetype and Registeractivatedclienttype.



Server-side activation objects are called server-activated because when the client uses new, only one agent is created. The actual object is created (activated) when it is known to invoke a method through a proxy. In other words, it is not the client who decides when to create a physical object. Client-activated objects are created on the server when the client uses new. This is the first difference.

The second difference is that client-activated objects can be activated using a Non-default constructor (a constructor with parameters). The server-side Opportunity object does not support Non-default constructors because using new simply creates a proxy and does not create a corresponding actual object. Client-activated objects can create both agents and objects through new.

The third difference is how the client and the object are linked. When registering the server to activate the object, you can specify the activation mode to decide whether to create an object instance for each request or to create an object instance to service all requests. Both of the activation modes are:

WellKnownObjectMode.SingleCall: Creates a unique object instance for each request.

Wellkonwnobjectmode.singleton: Create an object instance to service all requests

The appropriate activation mode is usually selected according to the environment. For example, if a remote object provides a "one-shot" service that does not require a state to be maintained between multiple invocations or does not need to be shared across all clients, then SingleCall is the right choice. Because each request produces a new object instance. If you want to pass data between clients, use Singleton.

A noteworthy place for a singleton object is the thread synchronization problem. When two clients call the object's methods at the same time, an error may occur, which is to be used. NET Framework provides a synchronization mechanism.



The client-activated object provides a third option. When a client-activated object is used, the object serves only for this client and can hold state across multiple invocations.



Single-call server-activated objects, singleton server-activated objects and client-activated objects provide three different activation modes. Use Single-call when you do not need to share the state on all clients. Use singleton when you want to share state with all clients. When all clients are not required to connect to the same object, the client-activated object is used whenever the client's own state is maintained.



program Example:

Stopwatch.cs

Using System;
public class Stopwatch:marshalbyrefobject
{
DateTime mark = DateTime.Now;
public void Start ()
{
Mark = DateTime.Now;
}
public int Stop ()
{
return (int) (Datetime.now-mark). TotalMilliseconds);
}
}
StopwatchServer.cs

Using System;
Using System.Runtime.Remoting;
Using System.Runtime.Remoting.Channels;
Using SYSTEM.RUNTIME.REMOTING.CHANNELS.TCP;
Class MYAPP
{
static void Main ()
{
TcpServerChannel channel = new TcpServerChannel (1234);
ChannelServices.RegisterChannel (channel);

Remotingconfiguration.registeractivatedservicetype
(typeof (Stopwatch));

Console.WriteLine ("Press Enter to terminate ...");
Console.ReadLine ();
}
}
StopwatchClient.cs

Using System;
Using System.Runtime.Remoting;
Using System.Runtime.Remoting.Channels;
Using SYSTEM.RUNTIME.REMOTING.CHANNELS.TCP;
Class MYAPP
{
static void Main ()
{
TcpClientChannel channel = new TcpClientChannel ();
ChannelServices.RegisterChannel (channel);
Remotingconfiguration.registeractivatedclienttype
(typeof (Stopwatch), "tcp://localhost:1234");
stopwatch SW = new Stopwatch ();
Sw. Start ();
Console.WriteLine ("Press Enter to show elapsed time ...");
Console.ReadLine ();
Console.WriteLine (SW. Stop () + "millseconds");
}
}
V. Activator.GetObject and Activator.CreateInstance methods

The new operator is not the only way to activate a remote object. NET Framework provides additional activation methods: GetObject and CreateInstance. They are all members of the System.activator class. GetObject is used to activate objects that are activated on the server side, while CreateInstance is used to activate objects that are activated at the client.

When you use GetObject or CreateInstance to activate a remote object, You no longer need to call Registeractivatedclienttype or Registerwellknownclienttype to register a remotable class on the server. For example, when activating an object that is activated on the server side:

Remotingconfiguration.registerwellknownclienttype (typeof (Clock), "Tcp://localhost:1234/clock");

Clock Clock = new Clock ();

You can use the following method generation

Clock Clock = (Clock) Activator.GetObject (typeof (Clock, "Tcp://localhost:1234/clock");

When activating a client object:

Remotingconfiguration.registeractivatedclienttype (typeof (Stopwatch), "tcp://localhost:1234");

stopwatch SW = new Stopwatch ();

Can be in this way:

object[] URL ={new urlattribute ("tcp://localhost:1234")};

stopwatch SW = (stopwatch) activator.createinstance (typeof (Stopwatch), null,url);

Why use them instead of new? Because when you only know the URL and the interface, GetObject and CreateInstance can still be used. Suppose you change the clock class, it implements a Iclock interface.

When using GetObject:

Iclock IC = (iclock) Activator.GetObject (typeof (Iclock), "Tcp://localhost:1234/clock");

If you use new, a compilation error occurs because new cannot accept an interface name:

Remotingconfiguration.registerwellknownclienttype
(typeof (Iclock), "Tcp://localhost:1234/clock");
Iclock IC = new Iclock ();



Vi. object lifetime and lease duration

A single-call server-side activation object survives only during method invocation. is then marked for deletion by the garbage collector. Singleton server-activated objects are not the same as client-activated objects, and their lifetimes are controlled by lease. A lease is an object that implements the ILease interface defined in the System.Runtime.Remoting.Lifetime namespace.

Singleton server-side activation objects and client-activated objects default leased objects have a 5 minute initialleasetime,2 minutes of renewoncalltime,5 minutes of CurrentLeaseTime. If the object has no method invoked, it is cleared when the CurrentLeaseTime is 0, which is cleared 5 minutes later.





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.