5th. Distributed System mode implement Broker through. NET Remoting using Server activation objects

Source: Internet
Author: User
Tags http authentication soap

Using the Microsoft. NET Framework to build an application that requires the use of distributed objects. Your requirements include being able to pass objects by value or by reference, whether they reside on the same computer, on different computers residing on the same local area network (LAN), or on different computers residing on a wide area network (WAN). The application does not require you to explicitly control the lifetime of the remote object.

Background information about. NET Remoting

Remoting uses object references to communicate between the client and the server. In the case of server activation, the client uses the remoting infrastructure (Activator.GetObject) to retrieve a reference to an existing server object. Once you have a reference to an object, you can call the object's method as if it were in your process and not running on a different computer. The following basic mechanisms are used to implement this functionality:

    • The client retrieves an instance of the remote type.
    • The remoting infrastructure creates a proxy object that acts as a remote type.
    • The client invokes the proxy method. The remoting system receives the call, routes it to the server process, invokes the server object, and then returns the result to the client proxy, which then passes the result to the client object.

The call itself must be sent in some way between the client and the server. The remoting infrastructure calls this mechanism a transport channel. Channels transport messages across remoting boundaries between applications, whether the boundary is between application domains, between processes, or between computers. The channel can listen for inbound messages on the endpoint, send outbound messages to another endpoint, or perform both tasks at the same time. This allows you to insert various protocols, even if the common language runtime is not on the other end of the channel.

Although the server process knows everything about each unique object, the client only knows that it needs to refer to an object in another application domain (possibly on another computer). From a scope outside the server application domain, the object is positioned through a URL.

Server activation

As described in the introduction to Distributed system clusters, the. NET Framework supports two activation models: Server activation and client activation. A server-activated object is an object whose lifetime is controlled directly by the server. The server application domain creates these objects only when the client invokes the method of the object, rather than when the client calls new or activator.getobject () , which reduces the network round-trip traffic that occurs just to create the instance. When a client requests an instance of a server-activated type, only one proxy is created in the client application domain. However, this also means that the server activation type only allows default constructors. If an instance of the type to be published is created with a specific constructor that needs to accept parameters, then client-side activation can be used.

In order to create instances of server-activated types, clients typically use Activator.GetObject ().

Select protocol and serialization mechanism

The type of protocol you choose affects how the application executes. For some criteria for choosing the correct channel type for your application, see the "Choosing Communication Options in. NET" topic in the. NET Framework Developer's Guide, which you can access to MSDN? Developer Program Website: http://msdn.microsoft.com/library/to learn about the content.

In this mode, you'll see two examples of Httpchannel/soap and tcpchannel/binary.

Implementation strategy

This mode provides two examples of server-activated objects, as well as the flexibility of the. NET Remoting infrastructure. The first example uses HttpChannel and its default serialization mechanism SOAP. The second example uses TcpChannel and its default binary serialization mechanism. Before we discuss the application itself, we first need to understand the classes that must be distributed across the network.

Server object

The RecordingsManager class has a method called Getrecordings , which retrieves a list of records from the database and returns the results in the DataSet. Note that there are a number of considerations involved when determining the best data type to transfer over a remote connection. The example uses a DataSet because its sample code is brief and shows how the complex data types are routed. For an in-depth discussion of this topic, see the MSDN article "Designing Data Tier and passing Data Through Tiers":

Http://msdn.microsoft.com/library/en-us/dnbda/html/BOAGag.asp

RecordingsManager.cs

The following example shows the RecordingsManager class:

Using System;

Using System.Data;

Using System.Data.SqlClient;

public class RecordingsManager

{

Public DataSet getrecordings ()

{

String selectcmd = "SELECT * from Recording";

SqlConnection myconnection = new SqlConnection (

"Server= (local);d atabase=recordings; Trusted_connection=yes ");

SqlDataAdapter mycommand =

New SqlDataAdapter (Selectcmd, MyConnection);

DataSet ds = new DataSet ();

Mycommand.fill (ds, "Recording");

return DS;

}

}

The class must be accessed remotely. First, theRecordingsManager class must inherit from a class in the remoting infrastructure named MarshallByRefObject . MarshalByRefObject is the base class for objects that communicate across application domain boundaries by using proxies to exchange messages. Objects that are not inherited from MarshalByRefObject are implicitly marshaled by value. When a remote application references an object that is marshaled by value, a copy of the object is passed across the remoting boundary. Because you want to communicate using a proxy method instead of a copy method, you need to inherit marshallbyrefobject. Second, you need to extract an interface from this class. Interfaces are necessary to reduce the dependencies between the client and the server, and the application can be better deployed. For more information, see "Deployment Considerations" later in this pattern.

IRecordingsManager.cs

The following is the code for the extracted IRecordingsManager interface:

Using System;

Using System.Data;

public interface IRecordingsManager

{

DataSet getrecordings ();

}

RecordingsManager.cs (enable remote support)

After changing RecordingsManager, get the following code:

public class Recordingsmanager:marshalbyrefobject, IRecordingsManager

{ /*  */ }

HttpChannel : SOAP Serialization

The primary motivation for selecting this channel and serialization mechanism is security and interoperability. With Microsoft Internet Information Services (IIS)-hosted HttpChannel, you can take advantage of the security features built into IIS and ASP. If you select any other channel, or select HttpChannel does not reside in IIS, you must provide your own security features. In addition, HttpChannel and SOAP serialization must be used to enable interoperability between different operating systems. However, because of the additional overhead required to use XML serialization and the use of HTTP protocols within IIS and ASP, selecting HttpChannel does not achieve the highest performance. For more information, see "Action Considerations" later in this pattern.

The following solution uses HttpChannel and SOAP serialization for the RecordingsManager class described earlier (see Figure 1).

Figure 1 HttpChannel Implementation

HttpServer.cs

Httpserver is a console application that creates a HttpChannel object and assigns Port 8100. The code then associates the name "Recordingsmanager.soap" with a RecordingsManager instance.

There are two activation modes for Server activation objects:Singleton and SingleCall.

The Singleton type can have only one instance at any time. If an instance already exists, all client requests are handled by that instance. If no instance exists, the server creates an instance and all subsequent client requests are handled by that instance.

The SingleCall type always has one instance for each client request. The next method call will be handled by another server instance, even if the previous instance has not been reclaimed by the system.

RecordingsManager uses Singleton activation mode, so only one RecordingsManager instance runs on the server. This process works well because the object has only one method to retrieve a set of predefined data. The last line ensures that the code exits after the user presses the Enter key. Please note that this may not be the best way to ensure that the program does not quit. If the program exits, the client will not be able to access the server object.

Using System;

Using System.Runtime.Remoting;

Using System.Runtime.Remoting.Channels;

Using System.Runtime.Remoting.Channels.Http;

public class Httpserver

{

static void Main (string[] args)

{

HttpChannel channel = new HttpChannel (8100);

ChannelServices.RegisterChannel (channel);

RemotingConfiguration.RegisterWellKnownServiceType (

typeof (RecordingsManager),

"Recordingsmanager.soap",

Wellknownobjectmode.singleton);

Console.ReadLine ();

}

}

HttpClient.cs

The client program calls the Remoting framework function Activator.GetObject (), which specifies the URL where the object resides and the type that should be returned. In the case of this example, theIRecordingsManager object should be in Http://localhost:8100/RecordingsManager.soap. Once you have an instance, you can invoke the instance's method as if it were in the same application domain.

Using System;

Using System.Data;

Using System.Runtime.Remoting;

Using System.Runtime.Remoting.Channels;

Using System.Runtime.Remoting.Channels.Http;

public class HttpClient

{

[STAThread]

static void Main (string[] args)

{

HttpChannel channel = new HttpChannel ();

ChannelServices.RegisterChannel (channel);

IRecordingsManager mgr = (irecordingsmanager)

Activator.GetObject (typeof (IRecordingsManager),

"Http://localhost:8100/RecordingsManager.soap");

Console.WriteLine ("Client.main (): Reference acquired");

DataSet ds = Mgr. Getrecordings ();

Console.WriteLine ("Recordings Count: {0}",

Ds. Tables["Recording"]. Rows.Count);

}

}

TcpChannel : Binary Serialization

The primary motivation for selecting this channel and serialization mechanism is performance. In fact, the use of binary serialization can significantly improve performance. (See "Action considerations".) If you do not have any security issues (for example, you are building a small application that is completely running inside the firewall), you should use TcpChannel and binary serialization, as this will get the best performance.

The following solutions use TcpChannel and binary serialization for the RecordingsManager class described earlier (see Figure 2).

Figure 2 Implementation of tcpchannel/binary serialization

TcpServer.cs

TCPServer is a console application that creates a TcpChannel object and assigns Port 8100. The code then associates the name "Getrecordingsmanager" with a RecordingsManager instance. The activation mode of RecordingsManager is Singleton, so only one RecordingsManager instance will run on the server. The last line ensures that the code exits after the user presses the Enter key. Please note that this may not be the best way to ensure that the program does not quit. If the program exits, the client will not be able to access the server object.

Using System;

Using System.Runtime.Remoting;

Using System.Runtime.Remoting.Channels;

Using SYSTEM.RUNTIME.REMOTING.CHANNELS.TCP;

public class TCPServer

{

static void Main (string[] args)

{

TcpChannel channel = new TcpChannel (8100);

ChannelServices.RegisterChannel (channel);

RemotingConfiguration.RegisterWellKnownServiceType (

typeof (RecordingsManager),

"Getrecordingsmanager",

Wellknownobjectmode.singleton);

Console.ReadLine ();

}

}

TcpClient.cs

The client program calls the Remoting framework method Activator.GetObject ()to retrieve the proxy for the RecordingsManager object on the server. This method specifies the URL where the object resides and the type that should be returned. In the case of this example, theIRecordingsManager object should be located at: Http://localhost:8100/GetRecordingsManager. Once you have an instance, you can call the instance's method as if it were in the same application domain.

Using System;

Using System.Data;

Using System.Runtime.Remoting;

Using System.Runtime.Remoting.Channels;

Using SYSTEM.RUNTIME.REMOTING.CHANNELS.TCP;

Class TcpClient

{

[STAThread]

static void Main (string[] args)

{

TcpChannel channel = new TcpChannel ();

ChannelServices.RegisterChannel (channel);

IRecordingsManager mgr = (irecordingsmanager)

Activator.GetObject (typeof (IRecordingsManager),

"Tcp://localhost:8100/getrecordingsmanager");

Console.WriteLine ("Client.main (): Reference acquired");

DataSet ds = Mgr. Getrecordings ();

Console.WriteLine ("Recordings Count: {0}",

Ds. Tables["Recording"]. Rows.Count);

}

}

Deployment considerations

When you use. NET Remoting, you must be careful when you deploy your application to different assemblies. The primary goal is to ensure that the code on the server is not delivered to the client. Figure 3 is a UML deployment diagram for the httpchannel/soap example.

Figure 3 structure of the HTTPCHANNEL/SOAP example

The example uses an assembly named IRecordingsManager , which is shared by both the client and the server. The assembly contains the IRecordingsManager interface, which defines the interface of the remote object that the client and server are sharing. In this example, theirecordingsmanager assembly is downloaded to the client.

Test

Writing tests for servers with Nunit is relatively straightforward. You can retrieve objects from the server and then call their methods as local objects. The following class tests the Httpserver class:

HttpServerFixture.cs

Using System;

Using System.Data;

Using System.Runtime.Remoting;

Using System.Runtime.Remoting.Channels;

Using System.Runtime.Remoting.Channels.Http;

Using Nunit.framework;

[Testfixture]

public class Httpserverfixture

{

Private IRecordingsManager Mgr;

Private HttpChannel channel;

private dataset DataSet;

[SetUp]

public void Loaddataset ()

{

Channel = new HttpChannel ();

ChannelServices.RegisterChannel (channel);

MGR = (IRecordingsManager)

Activator.GetObject (typeof (IRecordingsManager),

"Http://localhost:8100/RecordingsManager.soap");

DataSet = Mgr. Getrecordings ();

}

[Test]

public void Retrievedataset ()

{

DataTable recording = dataset.tables["Recording"];

Assertion.assertequals (4,recording. Rows.Count);

DataRow row = recording. Rows[0];

string title = (string) row["title"];

Assertion.assertequals ("Up", title. Trim ());

}

[TearDown]

public void Release ()

{

Channelservices.unregisterchannel (channel);

}

}

Result context

Using the server activation object to implement Broker with. NET Remoting has the following advantages and disadvantages.

Advantages

. NET Remoting provides a full-featured distributed object model with full common language runtime semantics that run on both the client and the server. The fidelity of the data passed between the client and the server is unaffected. This example shows how to pass a complex type System.Data.DataSet between a client and a server. It is not possible to implement such a pass if there are no common language runtimes at both ends of the connection.

Disadvantages

Some Broker benefits are affected by the following potential drawbacks:

    • The remote object . You must remember that these objects are remote objects. Even if they look like local objects, the overhead is still required to marshal the data back and forth from the server. Remember that remote calls are at least 1000 times times slower than local calls in the common language runtime. Therefore, you should make such a call only when you need it. Because of the need to minimize round-trips, this can cause you to not use the finest granularity when working with interfaces.
    • the complexity of the deployment . When using the server activation object described in the example, the object must already be registered before the client requests the object. This makes deployment more complex.
    • Limited Interoperability . You can use. NET Remoting to build Web Service. However, you must limit the endpoint to the simplest data type. For example, if you want to be able to interoperate with other Web Service toolkits, you must limit the parameters to built-in simple types and your own data types (do not use. NET Framework types, such as datasets), and use server-activated objects.
    • more complex . . NET Remoting is more difficult to learn, implement, and debug than a Web Service.

Safety considerations

To use the security features provided by Microsoft Internet Information Services (IIS) (for example, standard HTTP authentication scenarios, including Basic authentication, Digest authentication, digital certificates, and even Microsoft. NET Passport), you must use an HTTP-based Application, and the application should reside in IIS with an ASP. NET environment. If you want to use any other transport protocol, or use a HttpChannel other than IIS, you are required to provide a security mechanism.

Operational considerations

The following is a performance comparison of the MSDN article "performance Comparison:. NET Remoting vs. asp. NET Web Services" (. asp Remoting) [Dh An overview of performance comparisons in AWAN02]. This article concludes that you can achieve the highest performance by using TCP Channel and binary serialization, as well as the Windows service host. This configuration transmits binary data through the original TCP sockets, which is more efficient than HTTP. Its performance is 60% faster than the slowest method of HttpChannel, which uses SOAP serialization residing in IIS with ASP.

Residing in IIS can cause performance degradation because it involves additional process jumps from IIS (Inetinfo.exe) to aspnet_wp.exe. However, if you choose to host your channel without IIS and ASP, you need to provide your own authentication, authorization, and privacy mechanisms.

5th. Distributed System mode implement Broker through. NET Remoting using Server activation objects

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.