In-depth understanding of. NET Remoting and WebService

Source: Internet
Author: User
Tags soap soap client wsdl

1.. NET Remoting

. NET Remoting is Microsoft with . NET introduces a distributed application solution, known as the preferred technique for managing RPC between application Domains , which allows communication between different application domains (where communication can take place in the same process, between different processes of a system, and between processes in different systems).

More specifically,Microsoft. NET Remoting provides a framework that allows an object to interact with another object through an application domain. That is, with . NET Remoting, a program domain can access objects in another program domain, as if the object is inside itself, except that the code for the remote object is in the remote application domain, For example, calling a method on a remote object that pops up a dialog box on a local application domain, the dialog box pops up in the remote application domain.

The. NET Remoting Framework provides a variety of services, including activation and lifetime support, and communication channels that are responsible for message transmission with remote applications. The formatter is used to encode and decode a message before it is transmitted over the channel. Applications can use binary encoding in performance-focused situations and use XML encoding where they need to interact with other remoting frameworks . When you transfer messages from one application domain to another, all XML encodings use the SOAP protocol. For security reasons, remoting provides a number of hooks that enable a secure receiver to access messages and serialize streams before a message flow is transmitted over a channel.

. NET Remoting Collaboration capabilities

is the architecture diagram for. NET Remoting

. NET Remoting Communication architecture

In general,. NET Remoting includes the following key elements:

Ø remote object: The object that is running on the remoting server. The client indirectly invokes the service of the object through the proxy object, as shown in the communication architecture. In the . NET remoting system, to serve as a remote object, the class of the object must be a derived object of Marshbyrefobject. Also, it is important to note that objects that need to be passed on the network, such as "parameters", must be serializable.

Ø Channel: The channel is used for communication between the server and the client (the server and client are not necessarily computers or processes). In . NET remoting, three types of channels are available:TCP,HTTP,IPC, and alternatively, different channels can be customized to accommodate different communication protocols.

Ø message: The client and the server Exchange information through the message, and the message is passed through the channel. The message here includes information about the remote object, the calling method name, the parameter, the return value, and so on.

Ø format Identifier: The identifier indicates what format the message was sent to on the channel, and currently . NET 2.0 provides two format identifiers:SOAP format and binary format. SOAP format identifiers conform to the soap standard and are more generic and can communicate with non- . NET Framework Web Services. Binary format identifier, the speed, efficiency above the regeneration, but the versatility than soap poor. In addition,remoting supports custom format identifiers. (By the way: TheTCP channel is transmitted by default in binary format, because this is more efficient; TheHTTP channel uses the SOAP format by default, but in the system, which channel is used in which format, it can be set as needed.) )。

Ø format Identifier provider: It is used to associate a format identifier with a channel. When creating a channel, you can specify the identifier provider you want to use, and once the provider is specified, the format of the message sent to the channel is determined.

The

 .net remoting  provides two types of formatter sinks for serialized messages:  binaryformatter and Span lang= "en-us" >soapformatter. The type of selection depends largely on the type of network environment that is connected to the distributed object. Because .net remoting infrastructure. This flexibility enables the infrastructure to support a variety of possible line formats.  

For network transport protocols that can send and receive binary data (such as TCP/IP), you can use the System.Runtime.Serialization.Formatters.Binary defined in the The BinaryFormatter type. As the name implies,BinaryFormatter serializes the message object into a stream in a binary format. This is the most efficient and concise representation of the message object's transmission between the cables online. Some network transport systems do not allow the sending and receiving of binary data. This type of transmission forces the application to convert all binary data into an ASCII text representation before it is sent . In this case (or to get the best collaboration),. NET Remoting is available in the System.Runtime.Serialization.Formatters.Soap namespace The SoapFormatter type. The SoapFormatter uses the soap representation of the message to serialize the message to a stream.

Ø proxy object: As stated earlier, clients cannot directly invoke remote objects, and clients can only manipulate remote objects through proxy objects. Proxy objects, also divided into transparent agents and real agents. In the client's view, the proxy object and the remote object are the same. The client invokes the method on the transparent proxy object, and the transparent proxy invokes the Invoke method on the real proxy, and the Invoke method uses the message receiver to pass the message to the channel.

is an architecture diagram in which a client's method call causes the message to pass between channels:

The delivery process of the message on the channel

Ø message receiver: As shown, the message receiver is available on both the server side and the client, accepting the call of the real proxy and publishing the serialized message to the channel.

Ø Activator: This involves object lifetime management, where the client uses the activator to create a remote object on the server, or to request a reference to a remote object.

Ø RemotingConfiguration class: This class is used to configure a utility class for remote servers and clients that can be used to read configuration files or to dynamically configure remote objects. The point is thatmost of the properties and methods in the RemotingConfiguration class are static, which means that many properties, such as the application name, can only be set once by the current property or configuration file. If your application is running in a hosted environment, such as Internet Information Services (IIS), you might have set the value (which is usually set to a virtual directory). If the application name is not set, the current property returns a null reference.

Ø ChannelServices class: This class is used to register the channel and dispatch the message to the channel.

Below is a sample program for. NET Remoting, the structure of the sample project is as follows:

Where ClassLibrary is the class library of the remote object, Client, server is the console program.

The ClassLibrary code is as follows:

Using System;namespace classlibrary1{public    class Class1:marshalbyrefobject    {public         Class1 ()            : Base ()        {            Console.WriteLine ("Remote object is created! ");        }         ~class1 ()        {            Console.WriteLine ("The remote object is being refactored! ");        }        public void SayHello (string name)        {            Console.WriteLine ("Hello, {0}", name);        }        public int getsomthing (string s)        {            if (s!=null)            {                 Console.WriteLine ("I executed it! ");                return s.length;            }            return-1;}}}    

The relevant instructions are as follows:

1. Creation of remote objects

When the client obtains the server-side object, it does not get 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.

It is important to note that Class1 inherits from the MarshalByRefObject class, which is declared as a remote object. Please refer to MSDN for details on MarshalByRefObject.

The code for the server is as follows:

Using system;using system.runtime.remoting.channels.tcp;using system.runtime.remoting.channels;using System.runtime.remoting;using classlibrary1;namespace server{    class program    {//        <summary>        Server applications        //</summary>//<param name= "args" ></param>        static void Main (string[] args        {            //leverages the TCP channel and listens on 12345 port            tcpserverchannel channel = new TcpServerChannel (12345);            ChannelServices.RegisterChannel (channel, true);            Use the WellKnown activation method, and use the SingleCall mode            remotingconfiguration.registerwellknownservicetype (typeof (Class1), " Class1 ", wellknownobjectmode.singlecall);            Console.read ();}}}    

The relevant instructions are as follows:

1, remoting two kinds of channels

There are three main channels of remoting: TCP and HTTP and IPC. In. NET, the IChannel interface is defined in System.Runtime.Remoting.Channel. The IChannel interface includes the TcpChannel channel type and the HTTP channel type. They correspond to the first two types of remoting channels, respectively.

The TcpChannel type is placed in the namespace SYSTEM.RUNTIME.REMOTING.CHANNEL.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.Channel.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. IPC does not need the channel, suitable for native use, the speed can be imagined, faster than TCP and HTTP.

Usually we use TcpChannel in the LAN, and HttpChannel if we are going through the firewall. The IPC is preferred by the server and the client on the same host.

2. How to activate a remote object

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.

(1) 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.

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 the state management of ASP, we can think of it as a 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 draw on the status management of ASP, and think of it as a session state.

(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.

The code for the client is as follows:

 using system;using system.collections.generic;using system.linq;using system.text;using    System.runtime.remoting.channels.tcp;using system.runtime.remoting.channels;using ClassLibrary1;namespace Client{                Class Program {static void Main (string[] args) {try {//using a TCP channel connection                TcpClientChannel channel = new TcpClientChannel ();                ChannelServices.RegisterChannel (channel, true);                Gets the remote object Class1 class1 = (Class1) Activator.GetObject (typeof (Class1), "Tcp://localhost:12345/class1"); Method Class1 that invokes the remote object.                SayHello ("Debuglzq"); Class1.                SayHello ("Http://www.cnblogs.com/DebugLZQ"); int I=class1.                Getsomthing ("Debuglzq");            Console.WriteLine ("Input length is, {0}", i); } catch (Exception ex) {Console.WriteLine (ex.            Message);        } console.read (); }    }}

The running results of the program are as follows:
Server-side Run results

Client-side Run results:

Summary :Microsoft. NET Remoting provides a framework that allows an object to interact with another object through an application domain. That is, with . NET Remoting, a program domain can access objects in another program domain, as if the object is inside itself, except that the code for the remote object is in the remote application domain, For example, calling a method on a remote object that pops up a dialog box on a local application domain, the dialog box pops up in the remote application domain.

2.Web Service

Web service is also called an XML Web service. A WEB service is a lightweight, independent communication technology that can receive requests that are passed from the Internet or other systems on the intranet. is a software service provided through SOAP on the web, described using a WSDL file, and registered through UDDI.

XML: (extensible Markup Language) Extensible Markup Language. Temporary data processing for short-term, web-oriented network, is the basis of soap.

Soap: Simple Object access Protocol protocol. is the communication protocol for XML WEB Service. When a user finds your WSDL description document through UDDI, he can invoke one or more of the actions in the Web service that you set up by soap. SOAP is a specification for calling methods in the form of XML documents that can support different underlying interfaces, such as HTTP (S) or SMTP.

WSDL: (Web Services Description Language) A WSDL file is an XML document that describes a set of SOAP messages and how to exchange them. In most cases, it is automatically generated and used by the software.

UDDI (Universal Description, Discovery, and integration) is a new project primarily for Web service providers and users. Before a user can invoke a Web service, it is important to determine which business methods are included in the service, to find the called interface definition, and to prepare the software on the server side, and UDDI is a mechanism to guide the system through the description document to find the appropriate service. UDDI uses the SOAP message mechanism (standard xml/http) to publish, edit, browse, and find registration information. It uses XML format to encapsulate various types of data and send it to the registry or to the registry to return the required data.

The primary goal of WEB service is interoperability across platforms. To achieve this goal, Web Service is based entirely on platform-independent, software-vendor-specific standards, such as XML (Extensible Markup Language), XSD (XML Schema), and is a new platform for creating interoperable, distributed applications. So using Web Service has many advantages :

1. Cross-firewall communication

If the application has thousands of users and is distributed around the world, then communication between the client and the server will be a tricky issue. Because there is usually a firewall or proxy server between the client and the server. The traditional approach is to use a browser as a client, write down a lot of ASP pages, and expose the middle tier of the application to the end user. The result is that the development is difficult and the program is difficult to maintain. If client code is no longer so dependent on HTML forms, the client's programming is much simpler. If the middle-tier component is replaced with a Web service, the middle-tier component can be called directly from the user interface, eliminating the step of building an ASP page. To invoke a Web Service, you can directly use a SOAP client such as Microsoft SOAP Toolkit or. NET, or you can use your own SOAP client and then connect it to your application. It not only shortens the development cycle, but also reduces the complexity of the code and improves the maintainability of the application. At the same time, the application no longer needs to jump to the corresponding results page each time the middle-tier component is called.

2. Application integration

Enterprise-Class application developers know that it is common for businesses to integrate various programs that are written in different languages and run on different platforms, and that this integration will take a lot of development power. Applications often need to get data from programs running on one host, or send data to a host or other platform application. Even on the same platform, a variety of software produced by different software vendors often need to be integrated. With Web Service, applications can "expose" functionality and data in a standard way for use by other applications.

XML WEB Services provides the ability to exchange messages using standard protocols (HTTP, XML, SOAP, and WSDL) in a loosely coupled environment. Messages can be structured, typed, or loosely defined.

3, business-to-business integration

Business-to-business-to-business,as in businesses doing businesses with other businesses, businesses (generally referred to enterprises) of business e-commerce, that is, between enterprises and enterprises through the Internet products, Exchange of services and information. Popular parlance refers to the trade between the supply and demand of e-commerce business (or enterprises, companies), they use the Internet technology or a variety of business network platform to complete the process of business transactions.

Web Service is the key to the success of business-to-business integration. With Web service, companies can simply "expose" critical business applications to designated suppliers and customers, and Web service runs on the internet and can be easily implemented anywhere in the world, with relatively low operating costs. Web service is just a key part of business-to-business integration, and many other parts are needed to achieve integration. The greatest benefit of using Web service for business-to-business integration is the ease of interoperability. As long as the business logic is "exposed" and becomes a Web Service, it is possible for any designated partner to invoke these business logic, regardless of the platform on which their system runs, and what language to use. This greatly reduces the time and cost of spending on business-to-business integration.

4. Software and data reuse

Web Service can reuse the data behind the code while allowing reuse of the code. With Web service, it is no longer necessary to purchase, install, and invoke these components from a third party, just call the remote Web service directly, as you did before. Another kind of software reuse is the integration of the functions of several applications, through the Web Service "exposed", it is very easy to integrate all these features into your portal site, to provide users with a unified, user-friendly interface. You can use the functionality provided by a third-party Web service in your application, or you can make your own application functionality available to others through a Web service. In both cases, the data behind the code and the code can be reused.

As you can see from the above discussion, Web Service is most useful when it is interoperable or remotely invoked over the Web. However, there are cases where Web service does not bring any benefit at all, and Web service has the following drawbacks :

1. Stand-alone application

Today, businesses and individuals are also using many desktop applications. Some of them only need to communicate with other programs on this computer. In this case, it is best not to use the Web Service, as long as the local API. COM is well suited to working in this situation because it is both small and fast. This is also true for server software running on the same server. Of course, Web Service can also be used in these situations, but that not only consumes too much, but does not bring any benefits.

2. Some applications of LAN

In many applications, all programs use COM under the Windows platform, all running on the same LAN. In these programs, using DCOM is much more effective than soap/http. Similarly, if a. NET program is to connect to another. NET program on the local area network, you should use. NET Remoting. In fact, in. NET remoting, you can also specify that you use Soap/http to make Web Service calls. However, it is best to make RPC calls directly over TCP, which is much more effective.

Summary : From the architecture, the Web service is roughly divided into 5 levels:

1. HTTP Transport Channel
2. Data format FOR XML
3. SOAP Encapsulation Format
4. How WSDL is described
5. UDDI

Generally speaking, the WEB service structure under. NET is relatively simple and easy to understand and apply. WebService applications under the. NET structure are based on the. NET Framework and the IIS architecture, so deploying (Dispose) is relatively easy.

From the implementation point of view, first WebService must be exposed to the client's method in the class inherited from: System.Web.Services.WebService the base class, followed by the exposed method must be preceded by [WebMethod] or [ WebMethodAttribute].

Operation Mechanism of WebService
First the client from the server to the WebService WSDL, while the client claims a proxy class, this proxy class is responsible for the request and response with the WebService server, When a data (XML format) is encapsulated in a SOAP-formatted stream to the server, a process object is generated and the SOAP packet that receives the request is parsed, then the thing is processed, and the result is soap-wrapped after processing ends. And then the package as a response sent to the client proxy class, similarly, the proxy class will also parse the SOAP packet, followed by subsequent operations. This is a running process for webservice.

3..NET Remoting vs Web service comparison

1. NET Remoting uses HttpChannel, and can use the same HTTP protocol benefits as webservice, such as passing through firewalls. But WebService is a cross-platform, Java and. NET can provide each other and reference each other's webservice,.net remoting is limited to the. NET platform use.

2. NET Remoting is stateful, tightly coupled; the Web service is stateless (because HTTP is stateless), loosely coupled, and generally remoting suitable for use in LAN, where performance and responsiveness are more demanding; the web The service is suitable for cross-network, cross-system, high portability and universality requirements; Remoting and Web service strictly speaking is not the same technology as the EJB of the Java EE, if must compare, then deploy in the COM+/MTS. Net The remoting component can correspond to the EJB.

3,. NET The performance of remoting on the LAN is significantly stronger than Web services, using the TCP pipeline to transmit data without distortion, thus mitigating the work of serialization and deserialization, and of course, when using a Web service, A computer stores 32-bit integers differently than another computer, so you need a format that is easy to understand, such as XML. Web Services is performed by IIS, and. NET remoting is highly extensible, and using HTTP channels and XML can be part of the technology of Web services, and individuals feel that they can see Web service as a special case of. NET Remoting.

Conclusion

Whether it is a Web service or Microsoft.NET remoting can be said to be profound. The content of the entire Web service and remoting is not what I can do in this article, as the question shows, "Talk about" and welcome criticism!

In-depth understanding of. NET Remoting and WebService

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.