Friday 18 September 2009

.NET Remoting - Singleton SAO and CAO

Build a Remotable Type:

To build a remotable type, you just need to create a class which inherits from MarshalByRefObject.

SAO vs CAO:
  1. Client of SAO can call only the default constructor, whereas the client of CAO can call any custom constructor

...

Lease Time:

Lease time is the duration unto which object should remain in memory, preventing it from automatic garbage collection.

Singleton SAO would be garbage collected at the server if it remains inactive up to its default LEASE-BASE LIFETIME. Default time is 5 minutes for the first time and 2 minutes for the rest.

To change the default leave time:

public override Object InitializeLifetimeService()
{
ILease lease = (ILease)base.InitializeLifetimeService();
if (lease.CurrentState == LeaseState.Initial)
{
lease.InitialLeaseTime = TimeSpan.FromMinutes(1);
lease.SponsorshipTimeout = TimeSpan.FromMinutes(2);
lease.RenewOnCallTime = TimeSpan.FromSeconds(2);
}
return lease;
}

Infinite Timeout:

leave.InitialLeaseTime = TimeSpan.Zero;

Sinlgeton SAO

Singleton SAO remotable type - Config file - HTTP channel:

Hosting in a console app:

public class Listener{
public static void Main(){
RemotingConfiguration.Configure("Listener.exe.config");
}
}

app.config settings:

mode="Singleton"
type="RemotableType, RemotableType"
objectUri="RemotableType.rem"
Console Client:

public class Client{

public static void Main(){
RemotingConfiguration.Configure("Client.exe.config");
RemotableType remoteObject = new RemotableType();
}
}

"new" keyword creates a proxy on the client and client will work with that proxy to call the server remotable type.

App.config file:

type="RemotableType, RemotableType"
 
Singleton SAO - Using code - TCP channel:

Server:

TcpChannel channel = New TcpChannel(8080);
ChannelServices.RegisterChannel(channel, False);
RemotingConfiguration.RegisterWellKnownServiceType(RemotableType, "RemotableTypeUri", WellKnownObjectMode.Singleton);

Client:

RemotableType remotableType= (RemotableType) Activator.GetObject (typeof(RemotableType), "tcp://computername:8080/RemotableTypeUri");


CAO

Client Application - CAO - Using code - TCP channel:

RemotableType remotableType= (RemotableType)Activator.CreateInstance (typeof(RemotableType), null, "tcp://computername:8080/RemotableTypeUri")

The second argument is null which means no parameter is passed to create the instance.

CAO - Using Code - TCP channel:

Server:

ChannelServices.RegisterChannel(new TcpChannel(8082));
RemotingConfiguration.RegisterActivatedServiceType(typeof(RemotableType));

Client:

ChannelServices.RegisterChannel(New TcpChannel());
RemotingConfiguration.RegisterActivatedClientType(GetType(RemotableType), "tcp://localhost:8082");

RemotableType remotableType = new RemotableType();


More Info:

No comments: