Remoting: (This digest from Baidu Encyclopedia) Introduction: What is Remoting, in short, we can consider it as a distributed processing party Expression From the Microsoft product point of view, it can be said that remoting is an upgrade of DCOM, it has improved a lot of features, and excellent integration. NET platform. Microsoft. NET Remoting provides a framework that allows an object to interact with another object through an application domain. That's why we use Remoting. Why is it? In the Windows operating system, it is the separation of applications into separate processes. This process forms a boundary around the application code and data. If the interprocess communication (IPC) mechanism is not used, code executing in one process cannot access another process. This is an operating system protection mechanism for applications. In some cases, however, we need to cross the application domain and communicate with another application domain, that is, crossing the boundary. in remoting, the communication of objects between two applications and domains is achieved through channels (channel). First, the client accesses the channel to obtain the service-side object through remoting, and then resolves the client object through the proxy. This provides a possibility to publish server objects in a service-like manner. Remote object code can run on the server (such as server-activated objects and client-activated objects), then the client then connects to the server via remoting, obtains the service object, and runs through serialization on the client. in remoting, for objects to be passed, designers need not know the format of the packet in addition to the type and port number of the channel. This ensures loose coupling between the client and server-side objects, while optimizing the performance of the communication. Main element: remote Object--The remote object is the object that is running on the server. A client cannot invoke a method on a remote object directly, but instead uses a proxy. With. NET, it's easy to separate the remote object from the local object: that any class derived from MarshalByRefObject never leaves its application domain. The client can invoke methods of the remote object through the proxy. Channel--the channel is used for communication between the client and the server. The channel includes the channel portion of the client and the channel portion of the server. The. NET Framework 4 provides 3 Channel types, which communicate via TCP, HTTP, and IPC, respectively. In addition, you can create custom channels that communicate using other protocols. Message--The message is sent to the channel. The message is created for communication between the client and the server. The message contains information about the remote object, the name of the called method, and all the arguments. Formatter--the formatter is used to define how messages are transferred to the channel.. NET 4 has a SOAP formatter and a binary formatter. Use the SOAP formatter to communicate with Web services that are not based on the. NET Framework. The binary formatter is faster and can be used effectively in the intranet environment. Of course, you can also create a custom formatter. Formatter provider-the formatter provider is used to associate a formatter with a channel. By creating a channel, you can specify the formatter provider to use, and the formatter provider defines the formatter that is used when data is transferred to the channel. Proxy--the method by which the client invokes the proxy, not the remote object. There are two types of agents: transparent agents and real proxies. For clients, the transparent proxy looks similar to a remote object. On a transparent proxy, a client can invoke a method implemented by a remote object. The transparent proxy then invokes the Invoke () method on the real proxy. The Invoke () method uses a message sink to pass messages to the channel. message sink-The message sink is a listener (Interceptor) object, or receiver. There are listeners on both the client and the server. The receiver is associated with a channel. The real agent uses the message receiver to deliver the message to the channel, so the receiver can intercept the message before it enters the channel. Depending on where the receiver is located, the receiver can be called the Special Envoy Receiver (envoy Sink), the server context sink, the object context sink, and so on. Activator--The client can use the activator to create a remote object on the server, or to obtain a proxy for an object that is activated by the server. RemotingConfiguration Class--This class is a utility class for configuring remote servers and clients. It can be used to read configuration files or to dynamically configure remote objects. ChannelServicesClass-The class is a utility class that can be used to register a channel and assign a message to a channel. There are two main channels for [1] two channels: Remoting: TCP and HTTP. In. Net, the IChannel interface is defined in System.Runtime.Remoting.Channels. The IChannel interface includes the TcpChannel channel type and the HTTP channel type. They correspond to each of these two types of remoting channels. The TcpChannel type is placed in the namespace SYSTEM.RUNTIME.REMOTING.CHANNELS.TCP. The TCP channel provides a socket-based transport tool that uses the TCP protocol to transmit serialized message flows across the remoting boundary. The TcpChannel type uses binary format to serialize the message object by default, so it has higher transmission performance. The HttpChannel type is placed in the namespace System.Runtime.Remoting.Channels.Http. It provides a way to use the HTTP protocol to transmit a serialized message flow over the Internet through a firewall. By default, the HttpChannel type serializes the message object using SOAP format, so it has better interoperability. Usually we use TcpChannel in the LAN, and HttpChannel if we are going through the firewall. Activation mode:
Before accessing an object instance of a remote type, it must be created and initialized through a process called activation. This client creates a remote object through the channel, called the activation of the object. In remoting, the activation of remote objects falls into two main categories: server-side activation and client activation.
Server-side activation, also known as Wellknow mode, many are translated into well-known objects. Why is it called a well-known object activation mode? is because the server application publishes this type on a well-known Uniform Resource Identifier (URI) before activating the object instance. The server process then configures a WellKnown object for this type and publishes the object according to the specified port or address. Net Remoting the server-side activation is divided into singleton mode and SingleCall mode two kinds.
Singleton mode: This is a stateful mode. If set to singleton activation mode, remoting will establish the same object instance for all clients. When an object is active, the singleton instance processes all subsequent client access requests, whether they are the same client or another client. The singleton instance will maintain its state in the method call. For example, if a remote object has an additive method (I=0;++i), it is called by multiple clients (for example, two). If set to Singleton, the first customer gets a value of 1, and the second customer gets a value of 2 because the object instance they obtained is the same. If you are familiar with ASP. NET state management, we can think of it as a kind of application state.
SingleCall mode: SingleCall is a stateless mode. Once set to SingleCall mode, when the client invokes the method of the remote object, remoting establishes a remote object instance for each client, and the destruction of the object instance is automatically managed by the GC. As an example above, the two customers accessing the remote object received 1. We can still learn from ASP. NET state management, think of it as a session state.
client activation. Unlike wellknown mode, remoting assigns each client-activated type a URI when it activates each instance of the object. Client activation mode Once the client's request is received, an instance reference will be established for each client. There is a difference between the SingleCall mode and the client-activated mode: First, the object instance is created in a different time. Client activation is instantiated as soon as a request is made by the customer, and SingleCall is created when the object method is called. Second, the SingleCall mode activates an object that is stateless, the management of the object's lifetime is managed by the GC, and the client-activated object has a state and its life cycle can be customized. Three, the two activation modes on the server side and the client implementation method is different. Especially at the client, the SingleCall mode is activated by GetObject (), which invokes the object's default constructor. While the client-activated mode is activated by CreateInstance (), it can pass parameters, so you can call a custom constructor to create an instance.
Object definition: As mentioned earlier, when a client obtains a server-side object, it does not acquire the actual service-side object, but instead obtains its reference. Therefore, in remoting, there are some necessary definition specifications for remote objects to follow. Because the object passed by remoting is referenced, the remote object class passed must inherit MarshalByRefObject. MSDN's description of MarshalByRefObject is that 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. The remote objects that can be passed in remoting may be of various types, including complex dataset objects, as long as it can be serialized. Remote objects can also contain events, but server-side handling of events is special and I'll cover them in the third part of this series. Server: According to the first section, depending on the activation mode, the different server side of the channel type is implemented differently. Generally speaking, the server side should be divided into three steps:
1. Registration ChannelTo communicate across an application domain, you must implement a channel. As mentioned earlier, remoting provides a ichannel interface that contains TcpChannel and HttpChannel two types of channels respectively. These two types are implemented in exactly the same way except for the performance and serialization data formats, so let's take TcpChannel as an example. To register TcpChannel, first add the reference "System.Runtime.Remoting" to the project, and then the using namespace: SYSTEM.RUNTIME.REMOTING.CHANNEL.TCP. The code is as follows: TcpChannel channel = new TcpChannel (8080); ChannelServices.RegisterChannel (channel); The port number is passed as a parameter when the tunnel object is instantiated. Then call the static method RegisterChannel () to register the channel object.
2. Remote ObjectsAfter the channel is registered, the object must be registered in the channel to be able to activate the remote object. Depending on the activation mode, the methods for registering objects are different.
(1) Singleton modeFor WellKnown objects, you can use the static method RemotingConfiguration.RegisterWellKnownServiceType () to Now: RemotingConfiguration.RegisterWellKnownServiceType (typeof (Serverremoteobject.serverobject), "ServiceMessage", Wellknownobjectmode.singleton);
(2) SingleCall modeThe method of registering an object is basically the same as the singleton mode, and you only need to change the enumeration parameter WellKnownObjectMode to SingleCall. RemotingConfiguration.RegisterWellKnownServiceType (typeof (Serverremoteobject.serverobject), "ServiceMessage", WellKnownObjectMode.SingleCall);
(3) Activation modeFor the client activation mode, the method used is different, but the difference is not big, see the code at a glance. Remotingconfiguration.applicationname = "Servicemessage"; Remotingconfiguration.registeractivatedservicetype (typeof (Serverremoteobject.serverobject)); Why would you set the ApplicationName property before registering an object method? This property is actually the URI of the object. For the wellknown mode, the URI is placed in the parameters of the RegisterWellKnownServiceType () method and can of course be taken out specifically to assign a value to the ApplicationName property. In the overloads of the Registeractivatedservicetype () method, there are no applicationname parameters, so they must be separated.
3. Logout ChannelIf you want to turn off remoting services, you need to log out of the channel, or you can turn off monitoring of the channel. In the remoting when we register the channel, it automatically turns on the channel monitoring. If you turn off listening to the channel, the channel cannot accept the client's request, but the channel still exists and throws an exception if you want to register the channel again. Obtain the currently registered channel; ichannel[] Channels = channelservices.registeredchannels;//Close the channel named Mytcp; foreach (IChannel Eachchannel in Channels) {if (Eachchannel.channelname = = "Mytcp") {TcpChannel TcpChannel = (TcpChannel) Eachchannel; Turn off monitoring; tcpchannel.stoplistening (null); Logout channel; Channelservices.unregisterchannel (TcpChannel); }} code, the Registerdchannel property obtains the currently registered channel. In remoting, it is possible to register multiple channels at the same time, as explained later. Customer:
Client mainly do two things, one is to register the channel. As you can see from figure one, both the server side and the client in the remoting must pass the message through the channel to get the remote object. The second step is to get the remote object.
1. Registration Channel: TcpChannel channel = new TcpChannel (); ChannelServices.RegisterChannel (channel);*Note When a client instantiates a channel, it is the default constructor that is called, that is, the port number is not passed. In fact, this port number is integral, except that its designation is placed behind it as part of the URI.
2. Get the remote object:As with the server side, different activation modes determine how the client will be implemented differently. However, this difference is only the difference between the wellknown activation mode and the client activation mode, and the client implementation is identical for Singleton and SingleCall modes.
(1) wellknown activation mode to get servicesThe Activator process's GetObject () method to obtain: Serverremoteobject.serverobject ServerObj = ( Serverremoteobject.serverobject) Activator.GetObject (typeof (Serverremoteobject.serverobject), "tcp://localhost : 8080/servicemessage "); First activated in wellknown mode, the client obtains the object by using GetObject (). Where the first parameter is the type of the remote object. The second parameter is a server-side URI. If it's an HTTP channel, it's a natural use. Because I am using a local machine, so here is localhost, you can use the specific server IP address to replace it. The port must be the same as the server-side port. The following is the server-defined remote object service name, which is the contents of the ApplicationName property.
(2) Client activation mode As mentioned earlier, the wellknown mode can only invoke the default constructor when the client creates the object, as the above code illustrates, because the GetObject () method cannot pass arguments to the constructor. In the client-activated mode, you can create a remote object through a custom constructor. There are two methods of client activation mode: 1) Call RemotingConfiguration static method Registeractivatedclienttype (). This method returns a value of void, which simply registers the remote object on the client. The specific instantiation also requires invoking the constructor of the object class. Remotingconfiguration.registeractivatedclienttype ( typeof (Serverremoteobject.serverobject), "Tcp://localhost:8080/servicemessage"); serverremoteobject.serverobject serverobj = new Serverremoteobject.serverobject (); 2) Call the CreateInstance () method of the process activator. This method creates a method parameter that specifies the type of class object. It differs from the previous GetObject () in that it calls the constructor on the client, while GetObject () simply obtains the object, and the creation of the instance is done on the server side. The CreateInstance () method has a number of overloads, and I'll focus on the two commonly used ones. A, public static object CreateInstance (type type, object[] args, object[] activationattributes); Parameter description: TyPE: The type of object to create. Args: An array of parameters that match the number, order, and type of parameters of the constructor to invoke. If args is an empty array or a null reference (Nothing in Visual Basic), the constructor with no arguments is called (the default constructor). The parameter args here is a object[] array type. It can pass parameters in the constructor of the object to be created. From here you can actually get a conclusion: The remote object class passed by the WellKnown activation mode can only use the default constructor, while the activated mode allows the user to customize the constructor. The activationattributes parameter is typically used in this method to pass the server's URL. Suppose our remote object class Serverobject has a constructor: Serverobject (String pname,string psex,int pAge) {name = PName; sex = Psex; age = PAge; The code implemented is: object[] attrs = {new Urlattribute ("Tcp://localhost:8080/servicemessage")}; object[] Objs = new Object[3]; Objs[0] = "Wayfarer"; Objs[1] = "male"; OBJS[2] = 28; Serverremoteobject.serverobject = Activator.CreateInstance (typeof (Serverremoteobject.serverobject), objs,attrs); As you can see, the objs[] array is passed the arguments of the constructor. b, public static ObjectHandle CreateInstance (String assemblyname, String TypeName, object[] activationattribute); Parameter description: AssemblyName: The name of the assembly in which the type named TypeName will be looked up. If AssemblyName is a null reference (Nothing in Visual Basic), the assembly being executed is searched. TYpename: The name of the preferred type. Activationattributes: An array that contains one or more properties that can participate in activation. Parameter description at a glance. Note that this method returns a value of ObjectHandle type, so the code differs from the previous: object[] attrs = {new Urlattribute ("Tcp://localhost:8080/echomessage")}; ObjectHandle handle = Activator.CreateInstance ("Serverremoteobject", "Serverremoteobject.serverobject", attrs); Serverremoteobject.serverobject obj = (serverremoteobject.serverobject) handle. Unwrap (); This method is actually the default constructor for the call. The Objecthandle.unwrap () method is to return the wrapped object. Description: To use Urlattribute, you also need to add a using System.Runtime.Remoting.Activation in the namespace: Base Supplement: Through the above description, basically has completed a simplest remoting program. This is a standard way to create remoting programs, but in the actual development process, we encounter the situation may be strange, if only a so-called "standard", the delusion can "a recruit fresh, eat all over the day", is impossible.
1. Register multiple channelsIn remoting, multiple channels are allowed to be created at the same time, that is, different channels are created based on different ports. However, remoting requires that the name of the channel must be different because it is used as a unique identifier for the channel. Although IChannel has a ChannelName property, this property is read-only. Therefore, the method of creating the channel as described earlier cannot implement the requirement to register multiple channels at the same time. At this time, we must use the IDictionary interface in System.Collection: Register the TCP channel: IDictionary tcpprop = new Hashtable (); tcpprop["name"] = "tcp9090"; tcpprop["port"] = 9090; IChannel channel = new TcpChannel (Tcpprop, New Binaryclientformattersinkprovider (), New BinaryServerFormatterSinkProvider ()); ChannelServices.RegisterChannel (channel); Registering an HTTP channel: IDictionary httpprop = new Hashtable (); httpprop["name"] = "http8080"; httpprop["port"] = 8080; IChannel channel = new HttpChannel (Httpprop, New Soapclientformattersinkprovider (), New Soapserverformattersinkprovider ()); ChannelServices.RegisterChannel (channel); In the name attribute, it is possible to define a different channel name.
2. Remote object meta-data correlationBecause both the server side and the client use the remote object, the usual way is to generate two identical object DLLs, adding references separately. However, for the sake of code security, and to reduce the client's dependency on the remote object metadata, we need to change this way. The remote object is implemented on the server side, and the metadata for those implementations is removed at the client. Because of the different activation modes, the methods of creating objects in the client are different, so the correlation of metadata separation should also be divided into two cases.
(1) wellknown activation mode:implemented through interfaces. On the server side, provide interfaces and implementations of specific classes, while the client only provides interfaces: public interface Iserverobject {person Getpersoninfo (string name,string sex,int age); } public class Serverobject:marshalbyrefobject,iserverobject {...}*Note: The name of the assembly on both sides of the generated object must be the same, strictly speaking, the name of the namespace must be the same.
(2) Client activation mode:As mentioned earlier, for the client-activated mode, either using a static method or using the CreateInstance () method, the constructor instantiation object must be called on the client. Therefore, in the client we provide the remote object, we can not only provide the interface, and no implementation of the class. In fact, to be able to separate from the remote object metadata, there are two methods to choose from:
A. Use wellknown activation mode to simulate the client activation mode: By taking advantage of the "abstract factory" in design mode, the following class diagram describes the overall solution: we add an abstract factory interface and implementation class to the server-side remote object: public interface Iserverobject {person Getpersonin Fo (string name,string sex,int age); } public interface Iserverobjfactory {Iserverobject CreateInstance (); } public class Serverobject:marshalbyrefobject,iserverobject {public Person Getpersoninfo (string name,string sex,int Age) {Person person = new person (); Person. name = name; Person. sex = sex; Person. Age = age; return person; }} public class Serverobjfactory:marshalbyrefobject,iserverobjfactory {public Iserverobject CreateInstance () { return new Serverobject (); Then only the factory interface and the original object interface are available in the client's remote object: public interface Iserverobject {person Getpersoninfo (string name,string sex,int a GE); } public interface Iserverobjfactory {Iserverobject CreateInstance (); We register the remote object with WellKnown activation mode, on the server side://Pass the object; RemotingConfiguration.RegisterWellKnownServiceType (typeof ( serverremoteobject.serverobjfactory), "ServicEMessage ", WellKnownObjectMode.SingleCall); *Note that the Serverobject class object is not registered here, but rather the Serverobjfactory class object. Client: Serverremoteobject.iserverobjfactory serverfactory = (serverremoteobject.iserverobjfactory) Activator.GetObject (typeof (Serverremoteobject.iserverobjfactory), "Tcp://localhost:8080/servicemessage"); Serverremoteobject.iserverobject ServerObj = Serverfactory.createinstance (); Why is this a simulation of a client-activated mode? From the active method, we use the SingleCall mode to activate the object, but instead of activating the remote object we want to pass, the factory object is not active at this time. If the client is to create a remote object, it should also be obtained through the CreateInstance () method of the Factory object. And this method is called at the client. Therefore, it is implemented in the same way as the client activation mode.
B. Replacing metadata for remote objects with alternative classes In fact, we can use a trick to deceive remoting. The alternative class here is the trick. Since the service is provided, the details of the remoting passed by the remote object are, of course, placed on the server side. And to put a copy of the object on the client, but because the client must call the constructor, and take the frustration. Since the specific implementation is on the server side, and in order to be able to instantiate on the client, then this is done on the client side. As for the details of the implementation, there is no need to control it. If the remote object has a method, the server side provides the method implementation, and the client provides this method is OK, as for the implementation inside, you can throw an exception, or return a null value, if the method returns void, then the inside can be empty. The key is to have this method for the client class object. The implementation of this method is actually the same as the declaration of the method, so I say it is a trick. The method is the same with the constructor function. Or code to illustrate this "conspiracy", more intuitive: server-side: public class Serverobject:marshalbyrefobject {public Serverobject () {} public P Erson getpersoninfo (String name,string sex,int age) {Person person = new person (); Person. name = name; Person. sex = sex; Person. Age = age; return person; }} Client: public class Serverobject:marshalbyrefobject {public serverobj () {throw new System.notimplemente Dexception (); Getpersoninfo (String name,string sex,int age) {throw new System.NotImplementedException (); }} compare client and server side, client Method Getpersoninfo (), no specific implementation details, just throw an exception. Or simply write the statement return null, so OK. We call the GuestThis class of the client is an alternative class for the remote object.
3, using the configuration file implementationThe method described earlier, the settings for the server URI, port, and activation mode are done in code. In fact, we can also use the configuration file to set up. This is a good thing because this configuration file is an XML document. If you need to change the port or other, we do not need to modify the program and recompile, but only need to change the configuration file. (1) Server-side configuration file: <configuration> <system.runtime.remoting> <application name= "Serverremoting" > <service> <wellknown mode= "Singleton" type= "Serverremoteobject.serverobject" objecturi= "Servicemessage"/> </service> <channels> <channel ref= "tcp" port= "8080"/> </channels> </application> </system.runtime.remoting> </configuration> If it is a client-activated mode, change the wellknown to activated and delete the Mode property. Place the configuration file in the application folder of the server program, named Serverremoting.config. Then the previous server-side program directly with this statement: RemotingConfiguration.Configure ("Serverremoting.config"); (2) Client configuration file if it is a client-activated mode, the modification is the same as above. The call is also using the RemotingConfiguration.Configure () method to invoke the configuration file stored in the client. The configuration file can also be placed in the Machine.config. If the client program is a Web application, it can be placed in the. config.
4. Start/Close the specified remote object The remoting does not provide a method similar to Unregisterwellknownservicetype (), that is, once the remote object is registered, the object will remain in the channel if the channel is not closed. An object instance is created whenever the client activates the object. If the remoting transmits only one remote object, there is no problem, so close the channel. What if I transfer multiple remote objects? What should I do to close the specified remote object? What if you need to start after closing? We note that the marshal () and Disconnect () methods are provided in remoting, and the answer is here. The Marshal () method is to convert the MarshalByRefObject class object into a ObjRef class object, which is all the relevant information required to store the build agent to communicate with the remote object. This enables the client to serialize the instance so that it can be transferred between the application domain and over the network. The disconnect () method interrupts the specific instance object from the channel. The method is as follows: first register the channel: TcpChannel channel = new TcpChannel (8080); ChannelServices.RegisterChannel (channel); Then start the service: Instantiate the remote object on the server side first. Serverobject obj = new Serverobject (); Then, register the object. Note that there is no remotingconfiguration.registerwellknownservicetype (), but instead use Remotingservices.marshal (): ObjRef Objrefwellknown = Remotingservices.marshal (obj, "servicemessage"); If you want to unregister the object, then: RemotingServices.Disconnect (obj); Note that the class object disconnect here must be an object that was previously instantiated. Because of this, we can create the specified remote object as needed, and when closed, the object that was instantiated before disconnect. As for the client's invocation, the same method as the previous wellknown mode is still available through Activator.GetObject (). But from the implementation code, we will notice a problem, because the server side is explicitly instantiated the remote object, so regardless of how many clients, whether the same, they call the sameThe remote object. So we refer to this method as the simulated singleton pattern. Client activation mode We can also simulate the client activation mode through marshal () and disconnect (). First, let's review the section "remote object metadata dependencies", where I talk about using the "abstract factory" of design patterns to create object instances to emulate client-activated mode with SingleCall mode. Think carefully about the analog singleton pattern in front of you. Is the answer going to be on the horizon? In "simulated singleton" mode, we Marshal a specific remote object instance, which allows the client to obtain reference information for that object. So let's change the idea that when we use an abstract factory to provide an interface, the factory class implements the method of creating the remote object. Then we create the factory class instance on the server side. The factory class instance is then Marshal. Instead of getting the specific remote object, the client obtains the specific factory class object when it gets the object. Then call the CreateInstance () method to create the specific remote object instance. At this point, for multiple clients, the same factory class object is called, whereas the remote object is created on its own, so for remote objects it is activated by the client and a different object is created. When we want to start/close the specified object, we only need to use the Disconnet () method to unregister the factory class object. Summary: Microsoft. Net Remoting can really be said to be profound. The whole remoting is not the content of my this article can be described, it is not my remoting beginner can master. Wang Guowei in the "Human Cihua" a book, wrote: The Ancient and modern into the great cause of Brainiac, will pass through three realms. "Last night the West wind wither Green tree, alone on the high-rise, look at the end of the road. "This first realm also. "Emaciated end not regret, for Iraq to eliminate people haggard." "This second realm also. "The crowd looked for him 1100 degrees, suddenly looking back, the man was in the dim place." "This third realm is also. If this is to describe my study of remoting, still in the "high-rise, looking at the end of the road," the time, really can say has not presenting illegal weapons. Perhaps need to "emaciated", learn to Remoting "end not regret", just can "suddenly look back" bar.
. NET Remoting principles and application examples: