Use the .NET remote to access objects in other application domains.

zhaozj2021-02-17  54

Establish communication between objects running in different processes (whether on the same computer, or on a computer that is a computer) is a common development goal, especially when generating a wide range of distributed applications. Traditionally, this requires deep understanding of relevant knowledge: not only about the knowledge of the objects of communication, but also the knowledge of the host, application programming interface, and configuration tools or files on the low-level agreement. Briefly, it is a complex task that requires a lot of expertise and experience.

The .NET framework provides several communication methods that can be used quickly and easily, regardless of whether you have a lot of understanding of protocols and codes. Therefore, whether it is necessary to quickly develop web applications, still spend more time to generate key enterprise-wide applications (many computers or operating systems are involved in this process, and use multiple protocols and serialization optimization) ,. Net The framework will support your solution. Cross-process communication is still a complex task, but now many of its work is processed by .NET framework.

Select the communication option in .NET

The .NET framework provides several ways to communicate with objects in different application domains, each mode has specific levels of professionalism and flexibility. For example, the development of Internet has enabled XML Web Services a very attractive communication method because XML Web Services is based on the HTTP protocol used using XML and SOAP formatted general infrastructure. These are public standards and can be used directly with the current web infrastructure without having to worry about other agents or firewall issues.

However, if there is only a performance problem associated with SOAP serialization on an HTTP connection, it is not all applications to create some form of XML Web Services. The following subsections should help you determine where to use which form of objects to be used in the application.

Is ASP.NET or remote processing?

ASP.NET and .NET remote processing are all communication implementation methods between processes. ASP.NET provides an infrastructure carried by the Internet Information Services (IIS), which is good at handling basic types and is familiar to web application developers. .NET remote processing is a general and highly scalable process-inter-communication system that can be used to create XML Web Services in IIS (and all security, scalability, and sessions of ASP.NET and IIS) And application status) or any other type of communication.

The required communication type and the programming model you are familiar with are the main basis for choosing between the two programming models. Please first select the type of communication to the process you want, and then select the programming model that best implements your decision in the easiest way. The following is some of the basis for selecting the type of communication between the process you may need (sort by priority):

1. Safety needs. If you need to guarantee the security of the call, you must use the HTTP-based application beared in IIS, regardless of whether it is an ASP.NET application or remote processing applications. In IIS, applications based on ASP.NET and .NET remote processing have all security features you may need. Use any other transport protocol, or use HttpChannel outside IIS, you need you to complete your safety. Note that there is no need to use the SOAP encoding format when using the HTTP connection; you can use binary coding to increase the speed.

2. Speed. If the efficiency of each call is critical, binary encoding should be used, even if you don't use the default TCPChannel. In remote processing, you can use binary formatting programs and httpchannel; in ASP.NET, you can use POST communication. Single is to use binary formatting to significantly improve the call performance in remote processing, even if you are using HttpChannel. If there is no security issue (for example, if you are generating a small application that is running inside the firewall), the default TCPChannel using binary format can achieve optimal performance. 3. Interactive operation. If interactive operations must be performed in different operating systems, SOAP format protocols should be used whether or using the .NET remote processing or using ASP.NET.

4. Scalability. Regardless of whether .NET remote processing or ASP.NET, use the ASP.NET to get the application in IIS inside the IIS.

5. Random change. There are several questions that may be related to you, for example:

· The programming model is easy to use.

· Easy to achieve scalability.

· Custom needs.

· Use C managed to expand.

· Special needs for remote object activation, survival or user privileges.

· Do you need a complete type of fidelity.

The .NET remote processing system provides a solution for all of these requirements, while the ASP.NET system is only supported in some requirements.

The following is a short summary of some differences between XML web services generated using ASP.NET, System.Net Namespace and .NET Remote Processing.

XML Web SERVICES

If you are generating an ASP application, you want to use the web application model and the ability to support the ASP.NET HTTP runtime (including the powerful support in Microsoft Visual Studio .NET), you can meet your requirements using the web service generated by ASP.NET. . With the XML Web Services infrastructure, you can use the protocols, formats, and data types that are best suited to web-based applications to easily create your own components for other applications, or using the components created by others. It does not support the full type of fidelity between .NET computers, and only certain types of parameters can only be passed.

System.net namespace

You can use the class in the System.NET namespace from the category to generate the entire communication structure. You can also use the System.NET class to implement your own communication protocols and serialization formats that can be inserted into the remote processing structure.

.NET remote processing

.NET remote processing provides tools for implementing any number of comprehensive communication scenarios (including but not limited to XML Web Services). Use .NET remote processing:

Publish or use services in any type of application domain, whether the domain is a console application, Windows Form, Internet Information Services (IIS), XML Web Services or Windows services.

Keep the complete managed code type system fidelity in the communication in the binary format.

Note XML Web Services uses SOAP formatted, which does not maintain all type details.

By transmitting objects and returns a specific object in a particular application domain.

Direct control activation features and object survival.

Implement and use third-party channels or protocol to expand communications to meet specific requirements.

Participate in the communication process directly to create the required features.

.NET remote processing overview

You can use .NET remote processing to make different applications can communicate with each other, whether these applications are reside on the same computer, located in different computers in the same LAN (even if Computer runs different operating systems). The .NET framework provides a variety of services (such as activation and survival control), as well as communication channels responsible for transferring messages between local and remote applications. The formatter is used to encode and decode the message before the channel is sent. Applications can use binary encoding when performance is critical, or use XML encoding when interoperability with other remote processing systems is critical. Design for remote processing takes into account security, so you can use some hooks to access call messages and serialization streams to ensure they safely before passing them.

The remote processing infrastructure is an abstraction method of inter-process communication. Most of the system do not need to care at runtime. For example, an object that can be passed or can be copied is transmitted between an application on a different application domain or on a different computer. Simply mark the custom class as sequentialization.

However, the real advantage of the remote system is that it has the ability to communicate with each other in different application domains or processes (they use different transport protocols, serialization formats, object life solutions, and object creation modes). In addition, if it is for any reason, almost any stage of intervention communication process is required, remote processing makes this intervention possible.

Whether you have implemented some distributed applications, you can also easily understand the remote processing system as a general procedure communication system for interested in adding components to other computers. It has some default implementation that can easily handle most protocols. The following discussion begins with the basics of inter-process communication from the remote processing.

Copy and reference

Inter-process communication requires a server object that provides functions outside of its process, and a client that calls on the server object and a transmission mechanism that will call from one end to the other end. The address of the server method is a logical address and works normally in a process, but cannot work normally in other client processes. To resolve this issue, a method of the client call server object is to create a complete copy of the object and move the copy to the client process (the method can directly call the copy directly).

However, many objects cannot or should not copy and move to some other processes. Very large objects with many methods are not suitable for copying or passing to other processes. Typically, the client only requires information returned by one or several methods on the server object. Copy the entire server object (including a large number of internal information or executable structures that may be unrelated to client requirements) will be a waste of bandwidth and client memory and processing time. In addition, many objects disclose common functions, but require private data for internal execution. Copying these objects will enable malicious clients to view internal data to create security problems. Finally, some objects used by some objects cannot be copied in any understandable manner. For example, the FileInfo object contains a reference to the operating system file, which has a unique address in the memory of the server process. You can copy this address, but it will never have any meaning in another process.

In these cases, the server process should pass a reference to the server object to the client process, not a copy of the object. The client can use this reference to call the server object. These calls are not executed in the client process. In contrast, the remote processing system collects all information about the call and sends it to the server process. In this process, this information will be interpreted and the correct server object is found, and then the client object is sent to the server object. Then, the result of the call is sent back to the client process to return to the client. Bandwidth is only for critical information: call, call parameters, and any return value or exception.

Simplified remote processing structure

Use objects to communicate between server objects and clients to communicate with the core of remote processing. However, the remote processing structure provides a simpler process to programmers. If the client is configured correctly, you only need to create a new instance of the remote object using the New (or the instance creation function in the managed programming language). The client receives a reference to the server object, and then calls its method as the object is in your process instead of running on another computer. The remote processing system uses the proxy object to generate the effect of the server object in the client process. The agent is a temporary agent object that itself appears itself as a certain other object. When the client creates an instance of a remote type, the remote processing infrastructure creates a proxy object that looks exactly the same as the remote type. The client calls the method of this agent, and the remote processing system receives the call, route it to the server process, calls the server object, and returns the return value to the client agent, and the client agent returns the result to the client. Remote calls must be transmitted between clients and server processes in some way. If you want to generate a remote processing system yourself, you can start from learning network programming, a wide variety of protocols and serialization format specification. In the .NET remote processing system, the combination of the basic techniques required to open the network connection and send bytes to receive the byte to the receiving application are represented as transport channels.

The channel is a carrier data stream that creates a package according to a particular network protocol and sends the package to another computer. Some channels can only receive information, and some can only send information, and some (eg, default TCPChannel and HttpChannel classes) can be used in both directions.

Although the server process understands everything about each unique type, the client only knows that it requires a reference to an object in other applications (possibly on other computers). From the world outside the server application domain, the object is looking for through the URL. The only type of URL to the outside world is activated URL, which ensures that the remote call is emitted to the correct type.

Complete remote processing system design

Suppose your application runs on a computer, and you want to use the functions disclosed by the types stored on another computer. The following figure shows the conventional remote processing.

Remote processing process

If both ends of the relationship are configured correctly, the client only creates a new instance of a server class. The remote processing system creates a proxy object representing the class and returns a reference to the agent to the client object. When the client calls the method, the remote processing infrastructure should call, check the type information, and send the call to the server process through the channel. Listening channels get this request and forward it to the server remote processing system, the server remote processing system lookup (or created when necessary) and calls the requested object. Then, this process will be performed in reverse, the server remote processing system will respond to the bundle of messages and sent by the server channel to the client channel. Finally, the client remote processing system returns the result of the call to the client object via a proxy.

In order to make this process work only requires very little actual code, it should be carefully considered the design and configuration of the relationship. Even if the code is completely correct, it may still fail because the URL or port number is incorrect.

Although this high-level outline of the remote processing process is quite simple, low-level details may be very complicated. Other topics provide a more in-depth discussion of the main elements of remote processing, as shown in the topic listed below.

Remotely processed and non-remote processing objects

Please remember that it is created in an application domain and therefore specific to it can be called directly in this domain, but some special processes must be performed before this object can be used outside its domain. Not each type of object can be highly valued across the domain; therefore, it is necessary to decide which type of object to be published according to the needs of the application.

According to the purpose of distributed applications, there are two simple object categories: objects that can be remotely processed and non-remote processing. Objects that cannot be remotely processed do not provide replication them or any method thereof in other applications. Therefore, these objects can only be accessed from their original application domain. Objects that can be remotely processed can be accessed using both proxy applications or contexts, or copy them and can pass them to their application domains or context; in other words, some remote processing objects Others are passed by reference, while others are passed. Objects that are not remotely processed

Some objects cannot leave their application domains; they will never be blocked because they do not declare the serialization method. These non-remotely processed objects are dedicated to creating their same application domains and always access them directly from the same application domain. Most of the base classes in the .NET Framework class library are non-remote processing objects.

Objectable object

Objects that can be remotely processed are objects that can run in a wide range of distributed environments. There are two mainly remote processing objects:

Press value to enclose the object, they are copied and transmitted out of the application domain.

Press the reference to the encapsative, which will create a proxy, which is used by the client for remote access objects.

Press value to send objects

Press value to encapsulate (MBV) objects Declare their serialization rules (by implementing ISERIALIZABLE to implement their own serialization, or by modifying the system with SerializableAttribute, the property notifies the system automatically serialize the object), but does not extend MarshalByrefObject. The remote processing system creates a complete copy of these objects and passes a copy to the application domain that is called. Once the copy arrives in the application domain, the call to it is the direct call to the copy. Moreover, when the MBV object is passed as a parameter, it is passed through a value. In addition to declaring SerializableAttribute or implementing iSerializable, you can pass the class's instance across the application or context boundary by value through the value.

When the full state of the object and any executable functions are meaningless due to performance or processing, the MBV object should be used when moving to the target application domain. In many scenarios, this reduces the length and time-consuming round-trip of the network, process, and application domain boundaries. The MBV object can also be used directly from the original application domain of the object. In this case, because any encapsulation is not performed, no copy is created and the access is very efficient.

On the other hand, if the published object is very large, pass the entire copy on a busy network to the application may not be the best choice. In addition, changes to the status of the copy object will never pass back to the original object in the starting application domain. At the abstract level, this solution is similar to the scheme of the static HTML page requested by the client browser. Server copy file, write it into the stream, send it out, then forget it. All subsequent requests are just other requests for other copies.

The remote processing system uses a sequential object. References to objects in other application domains (represented by Objref classes in remote processing systems) itself is sequentially sequentially; must be able to accurately copy it and send copies to requests. Again, this is also because of the message object that implements iMessage, because they are general containers that call information and all other desired objects. In addition, only objects that transmit data are typically an MBV object. For example, the DataSet extension implements the MarshalByValueComponent for iSerializable.

According to the reference to the object

The object of the reference encapsulation (MBR) is the remote processing of the SYSTEM.MARSHALBYREFOBJECT is expanded. According to the declared activation type, when the client creates an instance of the MBR object in its application domain, the .NET remote processing infrastructure creates a proxy object indicating the MBR object in the caller's application domain, and calls Returns a reference to this agent. The client will then call it on the agent; remote processing seals these calls, send them back to the beginning of the application domain, and call the call on the actual object. Note If the client is located in the same application domain as the MBR object, the infrastructure returns a direct reference to the MBR object to the client, thereby avoiding the system overhead of the encapsulation.

If MARSHALBYREFOBJECT is incorporated as a parameter, it turns into another application domain when the call arrives. The MBR returns a value, and the OUT parameter works in the same way.

The MBR object should be used when the status of the object and any executable function should be in the application domain created. For example, an internal field and the internal field is an object of the operating system handle to extend MarshalByrefObject because the operating system handle is meaningless in other processes or other applications in other processes. Sometimes objects may be very difficult to imagine; for powerful servers, it is not possible to send to 33.6 kbps from the network.

Context binding object

The context binding object is an MBR object inherited from System.ContextBoundObject (which itself is inherited from System.MarshalByrefObject). The context is used as the sub-portion of the application domain, which provides a sufficient environment where the object that resides in execution is to provide a sufficient environment (for example, ensuring that the object will not be accessed simultaneously by multiple threads). Each application domain has default contexts, most managed code uses the default context of the application domain to create objects and call members directly from the same application domain without generating issues related to context. All types inherited from ContextBoundObject are disclosed to other contexts as agents, regardless of whether they are in the same application domain.

For example, it is assumed that there is a certain type of method that is part of the transaction is thus limited by the rules specific to the context of its context. This type should be inherited from ContextBoundObject so that the object can be accessed from the context of the object itself, and the system can enforce the rules of transactions associated with objects and their methods. If CONTEXTBOUNDOBJECT is called from the other context inside the same application domain, the agent will be created for the caller, but the communication between the context is not passed through the channel system, thereby increasing the call efficiency in this case.

Consider which category of how to remotely process, please decide which boundaries you need to pass. Objects specific to a particular context can only be accessed directly from the context. This is also true for objects specific to a particular application domain. To remotely process any of the objects in both, the remote processing system must successfully pass the two boundaries through the context boundary, application border or success before the server object is called within the boundary specific to the server object. . Since the processing time is taken through each boundary, it is necessary to determine which boundaries must pass in order to determine how the server should be the type of remote processing object. If you need to call an object without the context check, you should not let the remote type extending ContextBoundObject (MarshalByrefObject will be better). If you really need a context check, you should extend ContextBoundObject, but you need to understand that you must pass the additional boundary before the call is called.

Object activation and survival

In most cases, there is no need to pay attention to the exact time of the creation of objects; just make it respond when you call the method on the object. However, when generating a remote object, you must know when the new object and how to create and initialize, that is, how it is activated. The remote processing system must always know which type of activation is to be known before it is available for the client. Therefore, it is important to understand your choice. activation

There are two activation types: Server activation and client activation is activated by reference to encapsulation (MBR).

The object activated:

Create by the server when you need to create a client agent when you need to create a client agent by calling New or Activator.GetObject (), but is created when the client calls the first method on the agent.

It can be declared as a Singleton or SingleCall object. Singleton object is such an object: no matter how many clients have, there is only one example, and the object has the default life. When you declare an object as a SingleCall object, the system creates a new object for each client method. The client can use the survival lease system to participate in the survival period of these instances.

Objects to client activation:

The client calls new or activator.createInstance () to create it on the server. Using the survival lease system, the client itself can participate in the survival of these instances.

Survival rental

The object (MBR) by reference is referenced whether the server activated Singleton object or the client activated object, will never reside in memory. Instead, unless the type overwrites MarshalifeRefObject.initializelifetimeService () to control your own living life policy, each MBR's survival is controlled by the lease, lease manager, and some organizer. (In this case, the survival of the MBR object is the total time to maintain the active state in memory.) The lease itself is before the .NET remote processing system begins to delete a particular object and reclaim the memory process before the specific object is Time to maintain the active state in memory. The Lease Manager of the Server Application Domain is to determine when to mark the remote object for the object of garbage. The organizer can request a new lease object by registering itself to the lease manager.

As long as the MBR object is remotely processed outside the application domain, you create a survival lease for the object. Each application domain contains a lease manager responsible for managing a lease in its domain. The lease manager regularly checks all leases to determine the expired lease time. If the lease has expired, the Lease Manager will traverse its organizer list and request any of them to rely on it. If there is no hosted part, the lease manager will remove the lease, the object is deleted, and its memory is reclaimed by the garbage collection mechanism. Therefore, if the object is continuously rented by the organizer, the living period can be much longer than its survival period.

Since the survival of the remote object is independent of its client's survival, the lease of the simple or lightweight object (for an example) can be used by some clients, provided that the lease is rented by the manager or client regular renewal . This method uses the lease efficiently because the amount of network traffic required for distributed garbage collection is small. On the other hand, for the remote object of the use time and the remote object of the rare resource, the survival period of the lease can be short, so that the client is frequently renewed in its survival. When all clients complete the processing of the remote object, the .NET remote processing system will quickly delete the object. This strategy adds network traffic to use server resources more efficiently.

The survival of the rearisher management remote object is an alternative to the reference count, and the reference count may be complex and inefficient on unreliable network connections. Although the lease can be configured to extend the survival of the remote object exceeding the desired precise length, due to the reduction of network traffic dedicated to the reference count and the PING operation, the lease is made correctly when the specific scheme is correctly configured. A very attractive solution. Rent has five main properties:

InitialLeasetime. It specifies that the object will remain in the initial length of the memory before the lease manager starts to delete the object. In the configuration file, it is Configure the Leasetime property of the element. The default is 5 minutes. Lease time is zero, set the lease to an infinite life.

Currentleasetime. It specifies the length of time left before the lease expires. When the lease is renewed, its currentleasetime is set to the maximum value of the Currentleasetime or RenewonCallTime.

Renewoncalltime. It specifies the maximum length of time length to set the currentleasetime after each remote call to the object. The default is 2 minutes.

SponsorshipTimeout. It specifies that the lease manager is notified that the lease manager waits for the organizer to respond to the organizer. If the organizer does not respond within the specified time, remove the organizer and call another organizer. If there is no other organizer, the lease has expired, and the garbage collector will dispose of the remote object. If the value is "0" (Timespan.zero), the lease will not register the organizer. The default is 2 minutes.

LeasemanagerPollTime. It is the amount of time that the lease manager sleeps after checking the expired lease. The default LeaseManagerPollTime is 10 seconds.

Create a lease when the MBR object is activated in other application domains. At this point, when the ILASE.CURRENTSTATE property is LeaseState.Initial, the property can be set. Once set, you cannot change them directly. Change CurrentLeasetime can only be called from iLelease.Renew or when the lease manager calls isponsor.renewal on the organizer and the organizer uses a TimeSpan response. MarshalByrefObject has the default implementation of the survival lease, unless the lease is modified, otherwise the lease property will always be the same.

Modify the lease attribute

The living term lease attribute can be modified in two ways. You can declare that custom life lease properties is to rewrite MarshalByrefObject.initializelifetimeService in the MBR object, or rewrite it to returns NULL (Noth of Visual Basic) in your own. Nothing .NET Remote handling system This type of instance will have an infinitely long life. You or administrators can also specify the survival properties of all objects in the application in the element in a particular application or computer profile.

After the creation, you can use three ways to renew.

The client calls the lease.renew method directly.

If the ILASE.RENEWONCALLTIME attribute is set, each call to the remote object will be specified for the lease.

The lease calls isponsor.renewal method to request a renewal, and the organizer responds with a Timespan.

Lease manager

One of the Tasks of the Lease Manager is whether the time for regular check the lease has expired. When the rent of the lease has expired, the lease will receive a notification and try to renew ourselves by calling its organizer.

The Charter Manager also maintains a list of organizers who are waiting for their reply. If the organizer does not respond within the interval specified by the SponsorshipTimeout time, remove it from the organizer list.

When the lease is allowed to expire, it no longer accepts any other lease message or the content returned by the organizer. The reference to the lease is removed from the list of leases, and the .NET remote processing system will remove the object reference from its internal table. The garbage collection system will then remove the lease and object. channel

The channel is an object that transmits a message between the application between the application is transmitted across the remote processing boundary (whether in the application domain, process or between the computer). The channel can listen to the inbound message on the endpoint, send an outbound message to another endpoint, or both. This allows you to insert a wide variety of protocols, even if there is no public language running library on the other end of the channel.

The channel must implement an IChannel interface that provides information properties such as ChannelName and ChannelPriority. Designed To listen to the channel of the specific protocol on a particular port, IChannelReceiver is designed to send information to send information. TCPChannel and HTTPChannel are implemented for both interfaces, so they can be used to send or receive information.

You can register the channel to the remote processing infrastructure in two ways:

If you are publishing a remote processing, call ChannelServices.RegisterChannel () before the registration server object is registered.

If you are using the functionality of the remotely processed object, call ChannelServices.registerChannel () before creating an instance of the server object.

The channel can also be loaded from the remote processing profile.

At the client, the message is passed to the client channel receiving chain after the client is on the client. The first channel receiver is typically a formatting program receiver; it is sequenced into a stream (then the stream will be passed along the channel receiving chain to the client transmission receiver). The client transport receiver then writes this to the network.

On the server side, the server transmits the receiver from the network reads the request and passes the request stream to the server channel receiving chain. The server formatting program receiver of this chain ends into messages. This message is then passed to the remote processing infrastructure.

Channel selection

When the client is called, the parameters and the other details related to the call will be transferred to the remote object through the channel. Any result of the call returns in the same way. The client can select any channel to register on the server with remote objects so that developers can freely choose the channel that is most conforming to their needs. You can also customize any existing channels or generate new channels using different communication protocols. Channel selection needs to follow the following rules:

Before you can call the remote object, the remote processing system on the server must register at least one channel. The channel must be registered before the registration object. If there is no registration channel on the client, the remote processing system will select or create one to send the outbound call.

Note If the client needs a callback function, you must register a listening channel on the client and must configure the server to use a compatible channel.

The channel is registered for each application domain. A single process can contain multiple applications. When the process ends, all channels it registers automatically destroyed.

The channel name must be unique in the application domain. For example, since the default channel has a name, therefore, if you want to register two HTTPChannel objects in an application domain, you must change the name of the channel before registering them. The following C # code examples are demonstrated.

· IDictionary prop = new hashtable ();

· Prop ["name"] = "http1";

· PrOP ["port"] = "9001";

ChannelServices.RegisterChannel (new httpchannel (prop, null, null);

You cannot register multiple channels listening to a specific port multiple times. Although the channel is registered with each application domain, the different application domains on the same computer cannot be registered with the same channel listening on the same port. If you cannot determine if there is a portable port, use "0" (zero) when configuring the channel, and the remote processing system will select an available port.

The client can communicate with the remote object with any registered channel. The remote processing system will ensure that the remote object is connected to the correct channel when the client attempts to connect to a remote object. The client is responsible for calling ChannelServices.RegisterChannel () before attempting to communicate with the remote object, if the client needs a callback function, then it must register a channel and a port.

When the client is called when the method is called, the call will be intercepted and bundled into a message, and then passed to an instance of the RealProxy class. The REALPROXY class forwards messages to the message receiver for processing. The message receiver establishes a connection with a channel registered by a remote object and converts a message to the starting application domain through this channel. There, the message will be canceled and will call the remote object itself.

When remote processing initializes the proxy of the remote object in the client's domain, a message receiver that can communicate with the remote object is retrieved by calling the IChannelSender.createMessageSink configured on the selected channel.

A remote processing system is an easy-to-confusion aspects of remote objects and channels. For example, if an object is only activated when calling arrival, how will SingleCall Remote Objects listen to the client to connect?

This is possible, part of the reason is that the remote object sharing channel; the remote object does not have channel. The server application that hosts the remote object must register the channels they need and they want to use the objects disclosed by the remote processing system. After the channel registration, the client request will be automatically listened to the specified port. For synchronous calls, connections from the client will be maintained during the message call. Since each client connection is processed in its own thread, a single channel can serve simultaneously in multiple clients.

Remote processing example: asynchronous remote processing

The following sample application describes asynchronous programming in the remote processing scheme. This example first creates synchronization delegate of the remote object and calls it to explain the thread waiting for the returned. It then uses asynchronous commission and manualRestEvent to call remote object methods and wait for a response.

The app can run on a single computer or run over the network. If you want to run the application on the network, you must replace "LocalHost" in the client configuration with the name of the remote computer.

To generate this example, save the following file and type the following content at the command prompt:

CSC / T: Library /out:ServiceClass.dll ServiceClass.cs

CSC /R: SERVICECLASS.DLL SERVER.CS

CSC /R: SERVICECLASS.DLL Remoteasync.cs

Then, open two command prompts that point the same directory. Type one of them

Server

In another type:

Remoteasync

Remoteasync.cs

Using system;

Using system.reflection;

Using system.runtime.remoting;

Using system.runtime.remoting.Messaging;

Using system.runtime.remoting.channels;

Using system.threading;

Public Class RemotingDelegates: MarshalByrefObject {

Public Static ManualReveTevent E;

Public delegate string transotesyncDelegate ();

Public Delegate String RemoteasyncDelegate (); // this is the call That The asynccallback delegate Will Reference

[OneTtribute]

Public Void OurremoteasyncCallback (IASYNCRESULT AR) {

RemoteasyncDelegate Del = ((asyncResult) ((asyncResult) ar) .asyncdelegate;

Console.writeline ("/ r / n ** access **: Result of the remote asyncCallback:" DEL.Endinvoke (AR));

// Signal the thread.

E.SET ();

Return;

}

Public static void main (String [] args) {

// Important: Remember That .NET Remoting Does Not Remote

// static membs. this class must be an instance before

// the callback from the async invocation can take this client

RemotingDelegates Handlerinstance = New RemotingdeLegates ();

Handlerinstance.run ();

}

Public void run () {

// enable this and the e.waitone Call at the bottom if you

// is Going to make more Than You async Call.

e = new manualRetevent (false);

Console.writeline ("Remote Synchronous and asynchronous delegates.");

Console.writeLine (New String ('-', 80));

Console.writeLine ();

// this is the only Thing You Must Do IN a Remoting Scenario

// for Either synchronous or askronous programming - configuration.

RemotingConfiguration.configure ("SyncAsync.exe.config");

// Otherwise, from here on, the steps area identical to single-appdomain

// programming.

ServiceClass Obj = new serviceclass ();

// this delegate is a Remote Synchronous delegate

RemoteSyncDelegate RemoteSyncDel = New RemoteSyncDelegate (Obj.voidCall);

// when Invoked, Program Execution Waits Until Method Returns.

// this delegate Could Be Passed to Another Application Domain

// to be used as a callback to the obj.voidcall method.

Console.writeline (RemoteSyncDel ());

// this delegate is an asynchronous delegate. Two delegates must be created.// The first is the system-defined asyncCallback Delegate, Which References

// The method the remote type calls back when the remote method is done

AsyncCallback RemoteCallback = new asyncCallback (this.orRemoteasyncCallback);

// Now create the delegate to the remote method you want to use askMYNCHRONOSLY

RemoteasyncDelegate Remotedel = New RemoteasyncDelegate (Obj.timeconsumingRemoteCall);

// Now We Start The Method Call. Note That Execution On this Thread Continues

// immediately without waiting for the returnof.

IASYNCRESULT REMAR = RemoteDel.BeginInvoke (RemoteCallback, NULL);

// if at some point you want to stop execution on this thread to wait for

// The return from this specific call, Retrieve The IasyncResult Returned from

// the beginning of the beginivoke call, ketain its Waithandle, And Pause the Thread Until,

// Such as the next line:

// Remar.asyncwaithandle.waitone ();

// TO WAIT in General, IF, for Example, Many Asynchronous Calls Have Been

// Made and you want notification of any of them, or, like this example,

// Because The Application Domain Can Be Recycled Before The Callback

// can print the result to the console.

//e.waitone ();

// this Simulates Some Other Work Going On In this Thread While The Async

// Call Has Not Returned. if you're not doing Work on this thread,

INT count = 0;

While (! REMAR.IsCompleted) {

Console.write ("/ RNOT Completed:" ( count) .tostring ());

// Make Sure Callback Thread Can Invoke Callback

Thread.sleep (1);

}

}

}

Server.cs

Using system;

Using system.runtime.remoting;

Public class server {

Public static void main () {

RemotingConfiguration.configure ("Server.exe.config"); console.writeline ("waiting ...");

Console.readline ();

}

}

ServiceClass.cs

Using system;

Using system.runtime.remoting;

Public class serviceclass: MarshalByrefObject {

Public serviceClass () {

Console.writeline ("ServiceClass Created.");

}

Public string voidcall () {

Console.writeline ("VoidCall Called.");

Return "You are calling the void call on the serviceclass."

}

Public int getServicecode () {

Return this.gethashcode ();

}

Public string timeconsumingRemoteCall () {

"" TimeconsumingRemoteCall Called. ");

For (int i = 0; i <2000; i ) {

Console.write ("counting:" i.toString ());

Console.write ("/ r");

}

Return "this is a time-consuming call."

}

}

Server.exe.config

Wellknown

TYPE = "serviceclass, serviceclass"

Mode = "singleton"

Objecturi = "serviceclass.rem"

/>

Ref = "http"

Port = "8080"

/>

Syncasync.exe.config

Wellknown

TYPE = "serviceclass, serviceclass"

URL = "http:// localhost: 8080 / serviceclass.rem"

/>

Ref = "http"

Port = "0"

/>

to sum up

转载请注明原文地址:https://www.9cbs.com/read-28566.html

New Post(0)