Distributed Application in C#
Transcript of Distributed Application in C#
-
8/10/2019 Distributed Application in C#
1/11
Distributed Application in C# (.NETRemoting)
Introduction
.NET Remoting is a mechanism for communicating between obects which are not in the
same process. !t is a generic s"stem for dierent applications to communicate with oneanother. The applications can be located on the same computer$ dierent computers on the
same networ%$ or on computers across separate networ%s.
&icrosoft .NET Remoting pro'ides a framewor% that allows obects to interact with eachother across application domains. Remoting was designed in such a wa" that it hides the
most dicult aspects li%e managing connections$ marshaling data$ and reading and writing
&* and +,A-. The framewor% pro'ides a number of ser'ices$ including obect acti'ation
and obect lifetime support$ as well as communication channels which are responsible fortransporting messages to and from remote applications.
Remote ObjectsAn" obect outside the application domain of the caller should be considered remote$ e'en if
the obects are eecuting on the same machine. !nside the application domain$ all obects
are passed b" reference while primiti'e data t"pes are passed b" 'alue. +ince local obectreferences are onl" 'alid inside the application domain where the" are created$ the" cannot
be passed to or returned from remote method calls in that form. All local obects that ha'e
to cross the application domain boundar" ha'e to be passed b" 'alue and should bemar%ed with the [serializable] custom attribute$ or the" ha'e to implement the
ISerializableinterface. /hen the obect is passed as a parameter$ the framewor%
seriali0es the obect and transports it to the destination application domain$ where theobect will be reconstructed. *ocal obects that cannot be seriali0ed cannot be passed to a
dierent application domain and are therefore nonremotable.
An" obect can be changed into a remote obect b" deri'ing it from&arshal1"Ref,bect(Enables access to obects across application domain boundaries in
applications that support remoting). /hen a client acti'ates a remote obect$ it recei'es a
pro" to the remote obect. All operations on this pro" are appropriatel" indirected to
enable the Remoting infrastructure to intercept and forward the calls appropriatel".
In computer science, marshallingor marshalingis the process of transforming thememory representation of an objectto a data format suitable for storage or transmission,and it is typically used when data must be moved between dierent parts of a computer
program or from one program to another.
In computer science, in the context of data storage, serializationis the process oftranslating data structuresor objectstate into a format that can be stored (for example, ina leor memory buer, or transmitted across a networkconnection link and reconstructedlater in the same or another computer environment.
!his process of seriali"ing an object is also called marshallingan object.
http://en.wikipedia.org/wiki/Computer_sciencehttp://en.wikipedia.org/wiki/Object_(computer_science)http://en.wikipedia.org/wiki/Computer_sciencehttp://en.wikipedia.org/wiki/Data_structurehttp://en.wikipedia.org/wiki/Object_(computer_science)http://en.wikipedia.org/wiki/Computer_filehttp://en.wikipedia.org/wiki/Data_bufferhttp://en.wikipedia.org/wiki/Computer_networkhttp://en.wikipedia.org/wiki/Marshalling_(computer_science)http://en.wikipedia.org/wiki/Object_(computer_science)http://en.wikipedia.org/wiki/Computer_sciencehttp://en.wikipedia.org/wiki/Data_structurehttp://en.wikipedia.org/wiki/Object_(computer_science)http://en.wikipedia.org/wiki/Computer_filehttp://en.wikipedia.org/wiki/Data_bufferhttp://en.wikipedia.org/wiki/Computer_networkhttp://en.wikipedia.org/wiki/Marshalling_(computer_science)http://en.wikipedia.org/wiki/Computer_science -
8/10/2019 Distributed Application in C#
2/11
Types of .NET Remotable Objects
There are three t"pes of obects that can be con2gured to ser'e as .NET remote obects.
Single all
+ingle Call obects ser'ice one and onl" one re3uest coming in. +ingle Call obects areuseful in scenarios where the obects are re3uired to do a 2nite amount of wor%. +ingle Call
obects are usuall" not re3uired to store state information$ and the" cannot hold state
information between method calls.
Singleton Objects
+ingleton obects are those obects that ser'ice multiple clients$ and hence share data b"
storing state information between client in'ocations.
lient!"cti#ated Objects $"O%
Client4acti'ated obects (CA,) are ser'er4side obects that are acti'ated upon re3uest from
the client. The" can store state information between method calls for its speci2c client$ and
not across dierent client obects.
&omains!n .NET$ when an application is loaded in memor"$ a process is created$ and within thisprocess$ an application domain is created. The application is actuall" loaded in the
application domain. !f this application communicates with another application$ it has to use
Remoting because the other application will ha'e its own domain$ and across domains$
obect cannot communicate directl".
onte'ts
The .NET runtime further di'ides the application domain into contets. A contet is aboundar" that contains obects that share common runtime properties. Access re3uests
must be marshaled across contets.
(ro'ies
/hen a call is made between obects in the same Application Domain$ onl" a normal local
call is re3uired5 howe'er$ a call across Application Domains re3uires a remote call. !n orderto facilitate a remote call$ a pro" is introduced b" the .NET framewor% at the client side.
This pro" is an instance of the Transparent-ro" class$ directl" a'ailable to the client to
communicate with the remote obect. 6enerall"$ a pro" obect is an obect that acts inplace of some other obect. The pro" obect ensures that all calls made on the pro" are
forwarded to the correct remote obect instance. !n .NET Remoting$ the pro" manages the
marshaling process and the other tas%s re3uired to ma%e cross4boundar" calls. The .NETRemoting infrastructure automaticall" handles the creation and management of proies.
Real(ro'y and Transparent(ro'y
The .NET Remoting7ramewor% uses two pro" obects to accomplish its wor% of ma%ing aremote call from a client obect to a remote ser'erobect8 a Real-ro" obect and a
Transparent-ro" obect. The Real-ro" obect does the wor% of actuall" sending messages
to the remote obect and recei'ing response messages from the remote obect. TheTransparent-ro" interacts with the client$ and does the wor% of intercepting the remote
method call made b" the client.
http://www.csharphelp.com/archives2/archive424.html#%23http://www.csharphelp.com/archives2/archive424.html#%23http://www.csharphelp.com/archives2/archive424.html#%23http://www.csharphelp.com/archives2/archive424.html#%23 -
8/10/2019 Distributed Application in C#
3/11
)ars*alling
,bect &arshalling speci2es how a remote obect is eposed to the client application. !t isthe process of pac%aging an obect access re3uest in one application domain and passing
that re3uest to another domain. The .NET Remoting infrastructure manages the entire
marshaling process. There are two methods b" which a remote obect can be madea'ailable to a local client obect8 &arshal b" 'alue$ and &arshal b" reference.
)ars*alling objects by #alue
Marshal by value copies the entire object across application domain boundaries.The ser'er creates a cop"
of the obect and passes the cop" to the client. &arshal b" 'alue classes must either be
mar%ed with the 9+erilai0able: attribute in order to use the default seriali0ation$ or mustimplement the !+eriali0able interface.
)ars*alling objects by reference
/ith &arshal1"Ref,bect$ "ou are eecti'el" sharing the obect between the domains as areference. &arshal b" reference classes must inherit from +"stem.&arshal1"Ref,bect.
#arshalling is done by the .$%! &ramework itself. 'e dont have to write any code for it.
*annels
The .NET Remoting infrastructure pro'ides a mechanism b" which a stream of b"tes is sent
from one point to the other (client to ser'er etc.). This is achie'ed 'ia a channel. +trictl"
spea%ing$ it is a class that implements the !Channel interface. There are two pre4de2ned.NET Remoting channels eisting in +"stem.Runtime.Remoting.Channels$ the TcpChannel
and the ;ttpChannel. To use the TcpChannel$ the ser'er must instantiate and register the
Tcp+er'erChannel class$ and the client$ the TcpClientChannel class.
Channel selection is subect to the following rules8
At least one channel must be registered with the remoting framewor% before a
remote obect can be called. Channels must be registered before obects are
registered. Channels are registered per application domain. There can be multiple application
domains in a single process. /hen a process dies$ all channels that it registers are
automaticall" destro"ed.
!t is illegal to register the same channel that listens on the same port more than
once. E'en though channels are registered per application domain$ dierent
application domains on the same machine cannot register the same channel listening
on the same port.
-
8/10/2019 Distributed Application in C#
4/11
7ormatters are used for encoding and decoding the messages before the" are transported
b" the channel. There are two nati'e formatters in the .NET runtime$ namel" binar"
(+"stem.Runtime.+eriali0ation.7ormatters.1inar") and +,A-(+"stem.Runtime.+eriali0ation.7ormatters.+oap). Applications can use binar" encoding
where performance is critical$ or &* encoding where interoperabilit" with other remoting
framewor%s is essential.
.NET Remoting )etadata
.NET Remoting uses metadata to d"namicall" create pro" obects. The pro" obects thatare created at the client side ha'e the same members as the original class. 1ut theimplementation of the pro" obect ust forwards all re3uests through the .NET Remoting
runtime to the original obect. The seriali0ation formatter uses metadata to con'ert method
calls to pa"load stream and bac%.
The client can obtain the metadata information re3uired to access the remote obect in the
following wa"s8
The .NET assembl" of the ser'er obect.
The Remoting obect can pro'ide a /+D* (/eb +er'ices Description *anguage) 2le
that describes the obect and its methods.
.NET clients can use the +,A-+=D+ utilit" to download the &* schema from the
ser'er (generated on the ser'er) to generate source 2les or an assembl" that
contains onl" metadata$ no code.
Object "cti#ation
,bect acti'ation refers to the 'arious wa"s in which a remote obect can be instantiated.
&arshal b" 'alue obects ha'e a simple acti'ation scheme$ the" are created when the client2rst re3uests them. &arshal b" reference obects ha'e two acti'ation schemes8
Ser#er "cti#ated Objects
+er'er Acti'ated ,bectsare created onl" when the client ma%es the 2rst call to the remotemethod. !n other words$ when the client as%s for the creation of the remote obect$ onl" the
local pro" is created on the client$ the actual remote obect on the ser'er is instantiated on
the 2rst method call. These proies can be generated as8
7or +er'er Acti'ated ,bects$ the pro" obect (on the client) and the actual obect (on the
ser'er) are created at dierent times.
lient "cti#ated Objects
These are created on the ser'er immediatel" upon the client>s re3uest. An instance of a
Client Acti'ated ,bect is created e'er" time the client instantiates one$ either b" the use of
new or Acti'ator.Create!nstance(...).
Object ,ifetime and ,eases
A +er'er Acti'ated ,bect that has been registered as +ingelCall has a 'er" simple andlimited lifetime. !t li'es for a single call onl". Thereafter$ it is mar%ed for remo'al b" the
6arbage Collector.
The other two t"pes$ +ingleton and Client Acti'ated ,bects$ ha'e their lifetimes managedb" a ser'ice introduced b" the .NET 7ramewor%$ the *eased 1ased &anager. ,n the ser'er$
the application domain>slease manager determines when a ser'er4side obect should be
http://www.csharphelp.com/archives2/archive422.htmlhttp://www.csharphelp.com/archives2/archive422.html#%23http://www.csharphelp.com/archives2/archive422.htmlhttp://www.csharphelp.com/archives2/archive422.html#%23 -
8/10/2019 Distributed Application in C#
5/11
mar%ed for deletion. Each application domain has its own lease manager obect. 7or obects
that ha'e obect references that are transported outside the application$ a lease is created.
The lease has a lease time5 when the lease reaches 0ero$ it epires$ and the obect isdisconnected from the .NET Remoting 7ramewor%. ,nce all the references to the obect
within the AppDomain ha'e been freed$ the obect will be collected when the net garbage
collection occurs. A sponsor is another obect that pla"s a role in the life time. /hen a lease
has epired$ one or more of the lease>s sponsors are in'o%ed b" the *ease &anager$ wherethe" are gi'en the opportunit" to renew the lease. !f none of the sponsors decides to renew
the lease$ the lease manager remo'es the lease and the obect is garbage collected.
Rene-ing ,eases $Increasing ,ife Times%
/hile obects ha'e a default lease period$ there are man" wa"s to etend the lease period to%eep the obect ali'e$ in case the client wants to maintain state in the same ser'er obect.
,nce the obect has been marshaled$ the lease goes from the initial to the acti'e state$ and an"attempt to initiali0e the lease properties will be ignored (an eception is thrown).!nitiali0e*ifetime+er'iceis called when the remote obect is acti'ated. After acti'ation$ thelease can onl" be renewed.
The .NET Remoting implementation gi'es "ou two wa"s to renew the lease on a remote obect.The client can call !*ease.Renewdirectl"$ or the client can contact a sponsor and as% thesponsor to renew the lease.
The sponsor obect listens for 3ueries from the host s"stem>s lease manager$ and respondsaccordingl". +ponsors register with the lease manager b" obtaining a reference to the lease andcalling !*ease.Register. The lease manager will periodicall" 3uer" the sponsor to see if it wantsto renew the lease. !f the sponsor wants to renew the lease$ it returns a renewal Time+pan'alue in response to the ser'er>s 3uer".
+ponsors are preferable to client !*ease.Renewloops$ for se'eral reasons. 7irst$ the ser'er>slease manager %eeps trac% of when the obect>s lease is about to epire$ and will 3uer" the
sponsor as needed in order to ensure the opportunit" to etend the lease before time runs out.!t also is more ecient$ both in bandwidth and processing time. !n general$ where there aremultiple clients for a single remote obect (as in the case of a singleton)$ it is more ecient forthe lease manager to 3uer" a single obect for renewal rather than to ha'e each clientcontinuall" pinging the ser'er. This is also true in the case of client acti'ated obects because itreduces the networ% trac to ust the minimum re3uired to %eep the obect ali'e.
s the code$ which "ou should add to theremote client8
public Time+pan Renewal (!*ease lease)
-
8/10/2019 Distributed Application in C#
6/11
return Time+pan.7rom+econds(?@)5B
7inall"$ register the RemoteClientobect with the ser'er>s lease manager. !nsert the code belowwhere the ser'er>s obect instance is being created8
)) Instantiate the object
RemoteableClass &"Remot,bect new RemoteableClass()5)) register as a sponsor!*ease lease (!*ease)Remoting+er'ices.6et*ifetime+er'ice(&"Remot,bect)5lease.Register(this)5
;ow to !mplement Remoting
!n the following discussion$ we will discuss how we can implement remoting in our applications.The code gi'en in the discussion is ust to show what is necessar" in the code.
-
8/10/2019 Distributed Application in C#
7/11
!t is not necessar" to create the ser'er listener if "ou are planning to use !!+. 7or ob'iousreasons$ !!+ onl" supports the use of the ;ttpChannel. Create a 'irtual director" for "ourapplication$ and then put code to register "our ser'ice in the ApplicationF+tarte'ent.
7or our eample$ we>ll go ahead and create a ser'er listener$ in case "ou don>t ha'e !!+. +incethe ser'ice needs to be bound to an a'ailable port$ for our eample$ ! chose G@G@$ which is aport that ! %now to be unused on m" computer.
-
8/10/2019 Distributed Application in C#
8/11
pri'ate +"stem./indows.7orms.Tet1o tet1oI5&"Remotable,bect remote,bect5
pri'ate +"stem.Component&odel.Container components null5 public frmRCleint() !nitiali0eComponent()5 )) using !*+ protocol
)) running both client and server on same machines TcpChannel chan new TcpChannel()5 Channel+er'ices.RegisterChannel(chan)5
)) *reate an instance of the remote object remote,bect (&"Remotable,bect) Acti'ator.6et,bect( t"peof(&"Remotable,bect)$Htcp8localhost8G@G@;ello/orldH)5 B pri'ate 'oid tet1oIFTetChanged(obect sender$ +"stem.E'entArgs e) remote,bect.+et&essage(tet1oI.Tet)5 B BB
Running the Application
To run the application$ compile the Remoteable ,bect -roect obect. Compile ser'er applicationand run it. Compile the client application and run it. Two dialogue boes will appear8 one for theRemoting ser'er$ and one for the Remoting client. The Remoting ser'er will listen for there3uests. And the Remoting client is read" to pass the message to the ser'er. Now$ t"pe an"string in the client dialogue bo$ and the client will send it to the ser'er through Remoting$ andthe ser'er will displa" the string in the dialog bo of the ser'er application. This is a simpledemonstration of eas" and understandable Remoting.
,bect Con2gurations
There are two wa"s to con2gure remote obects. ,ne is b" code$ and the other is b" using acon2guration 2le$ both on the ser'er and the client. The ad'antage of using a con2guration 2leis we donJt ha'e to compile the code e'er" time we change the con2guration$ so we can changethe con2guration of the application at an" time without disturbing the code or eecutables. 1"con'ention$ the con2guration 2le name has the format executablename.cong.
onguration les
A t"pical con2guration 2le includes the following$ among other$ information8
;ost application information
Name of the obects
=R! of the obects
Channels being registered (multiple channels can be registered at the same time)
*ease time information for the ser'er obects
;ere is an eample the con2guration 2lename8
-
8/10/2019 Distributed Application in C#
9/11
Ser#er remoting conguration $server.exe.confg%/
Kcon2gurationL Ks"stem.runtime.remotingL Kapplication nameHser'erHL Kser'iceL Kacti'ated t"peHremote.+er'iceClass$ remoteHL Kser'iceL KchannelsL
Kchannel refHhttpH portHG@G@HL Kser'er-ro'idersL Kformatter refHbinar"H t"pe7ilter*e'elH7ullHL Kser'er-ro'idersL Kclient-ro'idersL Kformatter refHbinar"HL Kclient-ro'idersL KchannelL KchannelsL KapplicationL Ks"stem.runtime.remotingLKcon2gurationL
lient remoting conguration $client.exe.confg%
Kcon2gurationL Ks"stem.runtime.remotingL Kapplication nameHclientHL Kclient url Hhttp8localhost8G@G@HL Kacti'ated t"peHremote.+er'iceClass$ remoteHL KclientL KchannelsL Kchannel refHhttpH portH@HL Kser'er-ro'idersL Kformatter refHbinar"H t"pe7ilter*e'elH7ullHL Kser'er-ro'idersL Kclient-ro'idersL
Kformatter refHbinar"HL Kclient-ro'idersL KchannelL KchannelsL KapplicationL Ks"stem.runtime.remotingLKcon2gurationL
To use these con2guration 2les in our Remoting test application$ place those 2les (server.congand client.cong) in the director" that contains the server.exeand client.exeprograms.
=sing application con2guration 2les greatl" simpli2es the code re3uired to set up a remotingapplication. 7or eample$ the single line shown here ta%es the place of all the con2guration code
in the server.csprogram>s &ainmethod8
RemotingCon2guration.Con2gure(Hser'er.con2gH)5
The con2guration 2les shown set the client acti'ation44each client gets its own obect. !f "ouwant to con2gure for +ingleton mode$ change the Kser'iceLsection of the ser'er>scon2guration 2le so that it reads8
Kser'iceL
-
8/10/2019 Distributed Application in C#
10/11
Kwell%nown t"peHremote.+er'iceClass$ remoteH obect=riH+er'ice=R!H modeH+ingletonHLKser'iceL
And change the KclientLsection of the client>s con2guration 2le so that it reads8
Kclient url Hhttp8localhost8G@G@HL Kwell%nown t"peHremote.+er'iceClass$ remoteH urlHhttp8localhost8G@G@+er'ice=R!HLKclientL
onguration t*roug* code
Ser#er
Tcp+er'erChannel channel new Tcp+er'erChannel(rs.m-ort)5
Channel+er'ices.RegisterChannel(channel)5RemotingCon2guration.Register/ellnown+er'iceT"pe( t"peof(Remote+er'er,bect)$ HTestH$ /ellnown,bect&ode.+ingleCall)5
lient
TcpClientChannel chan new TcpClientChannel()5Channel+er'ices.RegisterChannel(chan)5!RemoteCom ob (!RemoteCom)Acti'ator.6et,bect(t"peof(!RemoteCom)$
Htcp8localhost8I@@MTestH)5
;osting .NET Remoting ,bects.NET Remoting obects can be hosted in8
&anaged eecutables
NET Remoting obects can be hosted in an" regular .NET EE or a managed ser'ice.
!!+
Remoting obects can be hosted in the !nternet !nformation +er'er (!!+). 1" default$ Remoting
obects hosted in !!+ recei'e messages through the ;TT- channel. 7or hosting Remoting obectsunder the !!+$ a 'irtual root has to be created$ and a H remoting.congH 2le has to be copied to it.The eecutable or D** containing the remote obect should be placed in the bindirector" underthe director" the !!+ root points to. !t is important to note that the !!+ root name should be thesame as the application name speci2ed in the con2guration 2les. The Remoting con2guration2le is automaticall" loaded when the 2rst message arri'es in the application.
.NET Component +er'ices
NET Remoting obects can be hosted in the .NET component ser'ices infrastructure to ta%ead'antage of the 'arious C,& ser'ices li%e Transactions$ O!T$ and ,bect pooling.
-
8/10/2019 Distributed Application in C#
11/11
&"Remotable,bect remote,bect5pri'ate +"stem.Component&odel.Container components null5public frmRCleint() !nitiali0eComponent()5 )) using !*+ protocol
)) running both client and server on same machines TcpChannel chan new TcpChannel()5 Channel+er'ices.RegisterChannel(chan)5 )) *reate an instance of the remote object
remote,bect (&"Remotable,bect) Acti'ator.6et,bect( t"peof(&"Remotable,bect)$Htcp8localhost8G@G@;ello/orldH)5Bpri'ate 'oid tet1oIFTetChanged(obect sender$ +"stem.E'entArgs e) remote,bect.+et&essage(tet1oI.Tet)5B
Running the Application
To run the application$ compile the Remotable ,bect -roect obect. Compile the ser'er
application and run it. Compile the client application and run it. Two dialog boes will appear$one for the Remoting ser'er and one for the Remoting client. The Remoting ser'er will listen forthe re3uests. And the Remoting client is read" to pass the message to the ser'er. Now$ t"pe inan" string in the client dialog bo$ and the client will send it to the ser'er through Remoting$ andthe ser'er will displa" the string in the dialog bo of the ser'er application. This is a simpledemonstration of eas" and understandable Remoting.