WCF Distributed Development Prerequisite Knowledge (2):. Net Remoting

Source: Internet
Author: User

. Net Remoting Technology , we can look at it as a distributed processing method. As a mechanism for communication between applications. Net Remoting is different from MSMQ Message Queuing, it does not support offline offline messaging and is only appropriate. NET platform for communication between programs. From the Microsoft product point of view, it can be said that remoting is a distributed component of DCOM upgrade, it has improved a lot of features, and excellent integration. NET platform. 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 you do not adopt the interprocess communication IPC (Internet process Connection) mechanism, 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 (refer to MSDN).

Now let's look at some of the more important concepts that are involved:

1. Channels (channel),

In. Net remoting, the communication of objects between two application domains is accomplished 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.

Channels (channel) There are 4 kinds of Strictly said, many data said there are 2-3 kinds. There should be 4 kinds. Httpchanel and Tcpchanel.

(1) HttpChannel. This channel can be used when a remote object resides in ASP. This channel uses the HTTP protocol to send messages between the client and the server. You can use the encryption mechanism in the HTTP protocol. Requires host name and port number.
(2) TcpChannel. When a remote object resides in an operating system service or other executable file, this channel uses a TCP socket to send messages between the client and the server. You also need to provide the host name and port number. does not provide any built-in security features.

(3) Ipcchanel, Interprocess Channel, uses only the communication within the same system, the visible process. The host name and port number are not required.
(4) Custom channel. A custom transport channel can use any basic transport protocol udp/smtp/ipx/Message Queuing mechanisms to communicate. Users can customize the way protocols as needed, so. Net Remoting is more flexible than other mechanisms. does not provide any built-in security features.

2. Remote Objects (Obeject)

In remoting, designers need to understand the format of the packet in addition to the type and port number of the channel. It is important to note, however, that when a client obtains a server-side object, it does not acquire the actual service-side object, but instead obtains its reference through the proxy. The remote object inherits from the MarshalByRefObject class, which enables the remote object to be used in the remoting application communication, supporting cross-domain boundary access to the object.

3. Activation mode

(1) server-side activation, also known as WellKnown, 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 based on the specified port or address. Server-side activation is also 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. 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.

(2) 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. (refer to MSDN for details)
(4) Agent proxy, the client access can not directly access the remote object, it is through the proxy to access the method on the proxy. The proxy object is divided into the transparent proxy and the real proxy, the difference is that on the transparent proxy, the client invokes the method of the real proxy on the remote object via invoke. And then pass the message to the channel. .

Well, here we have a basic understanding of. Net Remoting related knowledge, the following we learn is the specific programming implementation part. The program is broadly divided into 3 parts remote object/server/accessible. Now let's do it separately. Server side to add a reference The System.Runtime.Remoting assembly.

1. The remote object (Remoteoject), which is the object we want to access remotely. First, define a class, inherit MarshalByRefObject, and use it to support cross-domain boundary access for objects in remoting applications. The specific code is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacemodel{//creating remote objects, inheriting MarshalByRefObject, can be used in the remoting app to support cross-domain boundary access of objects     Public classMyremoteobject:marshalbyrefobject//accessing a remote object requires a proxy    {        //The method of implementing the addition function, the remote object can realize the operation of encapsulating business logic or data access.         Public intAddfortcptest (intAintb) {returnA +b; }        //to implement the subtraction function, test the HTTP channel         Public intMinusforhttptest (intAintb) {returnAb; }        //implements the multiplication function, tests the IPC channel         Public intMultipleforipctest (intAintb) {returnAb; }    }}

2 server-side, register the channel for interprocess communication, we register three kinds of channels here, namely Httpchanel/tcpchanel/ipcchanel. The code is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Runtime.Remoting;usingSystem.Runtime.Remoting.Channels;usingSystem.Runtime.Remoting.Channels.Http;usingSystem.Runtime.Remoting.Channels.Ipc;usingSYSTEM.RUNTIME.REMOTING.CHANNELS.TCP;usingSystem.Text;usingSystem.Threading.Tasks;usingModel;namespacenetremoting{classProgram {Static voidMain (string[] args) {            //creation of three channels//Create a TCP channel using port 10001TcpChannel chantcp =NewTcpChannel (10001); //Create an HTTP channel using the port 10002HttpChannel chanhttp =NewHttpChannel (10002); //To create an IPC channel, the IPC is only suitable for communication with processes within the system, so there is no need to set ports and host namesIpcChannel CHANIPC =NewIpcChannel ("YXLTESTIPC"); //Register Channel//registering a TCP channelChannelServices.RegisterChannel (CHANTCP); //registering an HTTP channelChannelServices.RegisterChannel (chanhttp); //Registering IPC ChannelsChannelServices.RegisterChannel (CHANIPC); ////////////////////////////////////////Print Channel/////////////////////////////////////////////////            //Print the name of the TCP channel.Console.WriteLine ("The name of the TCPChannel is {0}.", Chantcp.channelname); //prints the priority of the TCP channel.Console.WriteLine ("The priority of the TCPChannel is {0}.", chantcp.channelpriority); //the name of the print HTTP channel.Console.WriteLine ("The name of the HttpChannel is {0}.", Chanhttp.channelname); //the priority of the print HTTP channel.Console.WriteLine ("The priority of the HttpChannel is {0}.", chanhttp.channelpriority); //Print the name of the IPC channel.Console.WriteLine ("The name of the IpcChannel is {0}.", Chanipc.channelname); //prints the priority of the IPC channel.Console.WriteLine ("The priority of the IpcChannel is {0}.", chanipc.channelpriority); ///////////////////////////////////////////Registered Object/////////////////////////////////////////////////             //registering objects Myremoteobject to the net Remoting runtimeRemotingConfiguration.RegisterWellKnownServiceType (typeof(Myremoteobject),"Remoteobject.myremoteobject", Wellknownobjectmode.singleton); ///////////////////for Debug/////////////////////////////////////////////////////////////////////////Console.WriteLine ("Press any key to exit!");        System.Console.ReadLine (); }    }    }

Create a TCP channel, use port 10001, create an HTTP channel, use port 10002, create an IPC channel, and use port 10003,IPC only for communication with processes within the system, so you do not need to set the port and host name. Then call The static method of the ChannelServices class is registerchannel registered. The last step is to register the object Myremoteobject to the net Remoting runtime, Also configure the remote communication infrastructure first. The 2nd parameter is the URI of the object, "Remoteobject.myremoteobject", the client URL must match this, otherwise the exception that finds the proxy object is not found. Wellknownobjectmode.singleton); Remote object activation is a single-piece activation mode, each call to share an object, SingleCall activation mode will produce a new object each time it is called.

3 The client is a console program (the actual project type can be replaced, here just to select the console type as an example). The configuration file is set up as follows:

<Configuration>    <appSettings>         <AddKey= "Serviceurltcp"value= "Tcp://localhost:10001/remoteobject.myremoteobject"/>         <AddKey= "Serviceurlhttp"value= "Http://localhost:10002/RemoteObject.MyRemoteObject"/>         <AddKey= "SERVICEURLIPC"value= "Ipc://yxltestipc/remoteobject.myremoteobject"/>     </appSettings>   <system.runtime.remoting>      </system.runtime.remoting></Configuration>

usingSystem;usingSystem.Collections.Generic;usingSystem.Configuration;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingModel;namespacenetremotingclient{classProgram {[STAThread]Static voidMain (string[] args) {Myremoteobject proxyobjecttcp=(Myremoteobject) Activator.GetObject (typeof(Myremoteobject), configurationmanager.appsettings["serviceurltcp"]); //The method of accessing the object through the proxy, the output resultConsole.WriteLine ("This call object by tcpchannel,100+200 = {0}", Proxyobjecttcp.addfortcptest ( -, $)); Myremoteobject proxyobjecthttp=(Myremoteobject) Activator.GetObject (typeof(Myremoteobject), configurationmanager.appsettings["serviceurlhttp"]); //The method of accessing the object through the proxy, the output resultConsole.WriteLine ("This call object by httpchannel,100-200 = {0}", Proxyobjecthttp.minusforhttptest ( -, $)); Myremoteobject PROXYOBJECTIPC=(Myremoteobject) Activator.GetObject (typeof(Myremoteobject), configurationmanager.appsettings["SERVICEURLIPC"]); //The method of accessing the object through the proxy, the output resultConsole.WriteLine ("This call object by tcpchannel,100*200 = {0}", Proxyobjectipc.multipleforipctest ( -, $));         Console.readkey (); }    }}

WCF Distributed Development Prerequisite Knowledge (2):. Net Remoting

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.