[Transfer] A brief discussion on .net remoting and webservice

1. .NET Remoting

.NET Remoting is a distributed application solution launched by Microsoft with .NET. It is known as the preferred technology for managing RPC between application domains. It allows communication between different application domains (communication here can be within the same process, between different processes in one system, between processes in different systems).

More specifically, Microsoft .NET Remoting provides a framework that allows an object to interact with another object through the application domain. In other words, using .NET Remoting, one program domain can access an object in another program domain as if the object is located within itself. However, the code for calling this remote object is performed in the remote application domain. For example, if a method on a remote object that pops up a dialog box is called in the local application domain, then this dialog box will pop up in the remote application domain.

The .NET Remoting framework provides a variety of services, including activation and lifetime support, as well as communication channels responsible for message transfer with remote applications. Formatters are used to encode and decode messages before they are transmitted over the channel. Applications can use binary encoding when performance is important and XML encoding when interaction with other remoting frameworks is required. All XML encoding uses the SOAP protocol when transferring messages from one application domain to another. For security reasons, remoting provides a number of hooks that allow secure receivers to access the message and serialization streams before they are transmitted through the channel.

.NET Remoting interoperability

The following figure is the architecture diagram of .NET Remoting

      .NET Remoting communication architecture

Generally speaking, .NET Remoting includes the following main elements:

? Remote objects: objects running on the Remoting server. The client indirectly calls the service of the object through the proxy object, as shown in the “Communication Architecture” in the figure above. In the .NET Remoting system, in order to provide services for a remote object, the class of the object must be a derived object of MarshByRefObject. In addition, it should be noted that objects that need to be passed over the network, such as “parameters”, must be serializable.

? Channel: The channel is used for communication between the server and the client (the server and the client here are not necessarily computers, they may also be processes). In .NET Remoting, three channel types are provided: TCP, HTTP, and IPC. In addition, different channels can also be customized to adapt to different communication protocols.

? Message: The client and server exchange information through messages, and the messages are delivered in the channel. The message here includes remote object information, calling method name, parameters, return value, etc.

? Format identifier: This identifier indicates the format in which the message is sent to the channel. Currently, .NET 2.0 provides two format identifiers: SOAP format and binary format. The SOAP format identifier complies with the SOAP standard, is relatively universal, and can communicate with non-.NET framework Web services. Binary format identifiers are better in speed and efficiency, but are less versatile than SOAP. In addition, Remoting also supports custom format identifiers. (By the way: TCP channels use binary format transmission by default, because this is more efficient; Http channels use SOAP format by default; however, in the system, which channel uses which format can be set according to needs. ).

? Format identifier provider: It is used to associate format identifiers with channels. When creating a channel, you can specify the identifier provider to be used. Once the provider is specified, the format in which messages are sent to the channel is determined.

To serialize messages, .NET Remoting provides two types of formatter receivers: BinaryFormatter and SoapFormatter. The type chosen depends largely on the type of network environment connecting the distributed objects. Due to the pluggable nature of the .NET Remoting architecture, it is possible to create your own formatter receiver and plug it into the .NET Remoting infrastructure. This flexibility enables the infrastructure to support the various line formats possible.

For network transport protocols that can send and receive binary data (such as TCP/IP), you can use the BinaryFormatter type defined in the System.Runtime.Serialization.Formatters.Binary namespace. As the name suggests, BinaryFormatter serializes message objects into a binary format stream. This is the most efficient and concise representation of a message object being transmitted across a cable. Some network transmission systems do not allow binary data to be sent and received. This type of transfer forces the application to convert all binary data into an ASCII text representation before sending. In this case (or to get the best interoperability), .NET Remoting provides the SoapFormatter type in the System.Runtime.Serialization.Formatters.Soap namespace. SoapFormatter serializes a message into a stream using its SOAP representation.

? Proxy object: As mentioned before, the client cannot directly call the remote object, the client can only operate the remote object through the proxy object. Proxy objects are divided into transparent proxies and real proxies. From the perspective of the client, the proxy object and the remote object are the same. The client calls the method on the transparent proxy object, and the transparent proxy calls the Invoke method on the real proxy. The Invoke method then uses the message receiver to pass the message to the channel.

The following figure is an architectural diagram of a client’s method call that causes messages to be passed between channels:

The process of message delivery on the channel

? Message receiver: As shown in the figure above, message receivers are available on both the server and the client. They accept calls from the real agent and publish serialized messages to the channel.

? Activator: This involves object life cycle management. The client uses the activator to create a remote object on the server, or to apply for a reference to a remote object.

? RemotingConfiguration class: This class is a utility class used to configure remote servers and clients. It can be used to read configuration files or dynamically configure remote objects. One point to note is that most properties and methods in the RemotingConfiguration class are static, which means that many properties, such as application name, can only be set once through the current properties or configuration file. If the application is running in a hosted environment, such as Internet Information Services (IIS), this value may already be set (usually 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 messages to the channel.

Let’s write a .NET Remoting sample program. The structure of the sample project is as follows:

Among them, ClassLibrary is the class library of remote objects, and Client and Server are console programs.

The ClassLibrary code is as follows:

using System;
namespace ClassLibrary1
{
    public class Class1:MarshalByRefObject
    {
         publicClass1()
            :base()
        {
            Console.WriteLine("Remote object created!");
        }

         ~Class1()
        {
            Console.WriteLine("Remote object is destroyed!");
        }

        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;
        }

    }
}

Relevant instructions are as follows:

1. Creation of remote objects

When the client obtains the server-side object, it does not obtain the actual server-side object, but obtains its reference. Therefore, in Remoting, there are some necessary definition specifications for remote objects to be followed.

Since the object passed by Remoting is by reference, the remote object class passed must inherit MarshalByRefObject. MSDN’s description of MarshalByRefObject is: MarshalByRefObject is the base class for objects that communicate across application domain boundaries by using proxies to exchange messages. Objects that do not inherit 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 proxy methods instead of copy methods, you need to inherit MarshallByRefObject.

It should be noted that Class1 inherits from the MarshalByRefObject class, that is, it is declared as a remote object. For details about MarshalByRefObject, please refer to MSDN.

The server code 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 application
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //Use the TCP channel and listen to port 12345
            TcpServerChannel channel = new TcpServerChannel(12345);
            ChannelServices.RegisterChannel(channel, true);
            //Use WellKnown activation method and use SingleCall mode
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(Class1), "Class1", WellKnownObjectMode.SingleCall);
            Console.Read();
        }
    }
}

Relevant instructions are as follows:

1. Two channels of Remoting

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

The TcpChannel type is placed in the namespace System.Runtime.Remoting.Channel.Tcp. The Tcp channel provides a Socket-based transmission tool that uses the Tcp protocol to transmit serialized message streams across Remoting boundaries. The TcpChannel type uses binary format to serialize message objects 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 serialized message streams across firewalls on the Internet. By default, the HttpChannel type serializes message objects using Soap format, so it has better interoperability. IPC does not require a channel and is suitable for local use. As you can imagine, IPC is faster than Tcp and HTTP.

Usually in the LAN, we use TcpChannel more; if we want to traverse the firewall, we use HttpChannel. The server and client are on the same host, and IPC is given priority.

2. How to activate remote objects

Before accessing an object instance of a remote type, it must be created and initialized through a process called Activation. This kind of client creates remote objects through channels, which is called object activation. In Remoting, the activation of remote objects is divided into two categories: server-side activation and client-side activation.

(1) Server-side activation, also called WellKnow method, many are also translated as well-known objects. Why is it called well-known object activation mode? This is because the server application publishes the type on a well-known Uniform Resource Identifier (URI) before activating the object instance. The server process will then configure a WellKnown object for this type and publish the object based on the specified port or address. .Net Remoting divides server-side activation into SingleTon mode and SingleCall mode.

SingleTon mode: This is a stateful mode. If set to SingleTon activation mode, Remoting will create the same object instance for all clients. While the object is active, the SingleTon instance handles all subsequent client access requests, regardless of whether they are the same client or other clients. SingleTon instances will maintain their state across method calls. For example, if a remote object has an accumulate method (i=0; + + i), it is called by multiple clients (for example, two). If set to SingleTon mode, the first customer gets a value of 1, and the second customer gets a value of 2, because the object instances they get are the same. If you are familiar with Asp.Net’s state management, we can think of it as an Application state.

SingleCall mode: SingleCall is a stateless mode. Once set to SingleCall mode, when the client calls the method of the remote object, Remoting will create a remote object instance for each client, and the destruction of the object instance is automatically managed by the GC. For the same example as above, both clients accessing the remote object get 1. We can still learn from Asp.Net’s state management and think of it as a Session state.

(2) Client activation. Unlike the WellKnown pattern, Remoting assigns a URI to each client-activated type when activating each object instance. Once the client activation mode obtains the client’s request, an instance reference will be established for each client. There are differences between the SingleCall mode and the client activation mode: First, the object instances are created at different times. The client activation method is to instantiate once the client makes a call request; while SingleCall waits until the object method is called before creating it. Secondly, the objects activated by the SingleCall mode are stateless, and the management of the object life cycle is managed by the GC, while the objects activated by the client are stateful and their life cycles can be customized. Third, the two activation modes are implemented differently on the server side and client side. Especially on the client side, SingleCall mode is activated by GetObject(), which calls the object’s default constructor. The client activation mode is activated through CreateInstance(), which can pass parameters, so a custom constructor can be called to create an instance.

The client code 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
            {
                //Connect using TCP channel
                TcpClientChannel channel = new TcpClientChannel();
                ChannelServices.RegisterChannel(channel, true);
                //Get the remote object
                Class1 class1 = (Class1)Activator.GetObject(typeof(Class1), "tcp://localhost:12345/Class1");
                //Call the method of the remote object
                class1.SayHello("DebugLZQ");
                class1.SayHello("http://www.cnblogs.com/DebugLZQ");

                int i=class1.GetSomthing("DebugLZQ");
                Console.WriteLine("The input length is, {0}", i);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message );
            }
            Console.Read();
        }
    }
}

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

Client running results:

Summary: Microsoft .NET Remoting provides a framework that allows one object to interact with another object through the application domain. In other words, using .NET Remoting, one program domain can access an object in another program domain as if the object is located within itself. However, the code for calling this remote object is performed in the remote application domain. For example, if you call a method on a remote object that pops up a dialog box in the local application domain, then this dialog box will pop up in the remote application domain.

 2.Web Service

Web Service is also called XML Web Service. Web Service is a lightweight independent communication technology that can receive requests passed from the Internet or other systems on the Intranet. It is a software service provided on the Web through SOAP, described using WSDL files, and registered through UDDI.

XML: (Extensible Markup Language) Extensible Markup Language. For short-term temporary data processing and the World Wide Web, it is the foundation of Soap.

Soap: (Simple Object Access Protocol) Simple Object Access Protocol. It is the communication protocol of XML Web Service. When the user finds your WSDL description document through UDDI, he can call one or more operations in the Web service you created through SOAP. SOAP is a specification for calling methods in the form of XML documents. It 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 these messages. In most cases automatically generated and used by software.

UDDI (Universal Description, Discovery, and Integration) is a new project mainly aimed at Web service providers and users. Before users can call a Web service, they must determine which business methods are included in the service, find the called interface definition, and compile software on the server side. UDDI is a mechanism that guides the system to find the corresponding service based on the description document. UDDI uses SOAP message mechanism (standard XML/HTTP) to publish, edit, browse and search registration information. It uses XML format to encapsulate various types of data, and sends it to the registration center or the registration center returns the required data.

The main goal of Web Service is cross-platform interoperability. In order to achieve this goal, Web Service is completely based on platform-independent and software vendor-independent standards such as XML (Extensible Markup Language) and XSD (XML Schema). It is a new platform for creating interoperable and distributed applications. . Therefore, using Web Service has many advantages:

1. Communication across firewalls

If an application has thousands of users distributed around the world, communication between the client and server can be a tricky problem. Because there is usually a firewall or proxy server between the client and the server. The traditional approach is to choose to use the browser as the client, write a lot of ASP pages, and expose the middle layer of the application to the end user. The result of this is that development is difficult and the program is difficult to maintain. Client-side programming would be much simpler if client-side code no longer relied so much on HTML forms. If the middle-tier component is replaced by a Web Service, the middle-tier component can be called directly from the user interface, thus eliminating the step of creating an ASP page. To call a Web Service, you can directly use a SOAP client such as Microsoft SOAP Toolkit or .net, or you can use a self-developed SOAP client and then connect it to the application. Not only does it shorten the development cycle, it also reduces code complexity and enhances the maintainability of the application. At the same time, the application no longer needs to jump to the corresponding “result page” every time it calls the middle-tier component.

2. Application integration

Enterprise-level application developers all know that enterprises often have to integrate various programs written in different languages and running on different platforms, and this integration will cost a lot of development efforts. Applications often need to obtain data from a program running on a host; or send data to the host or other platform applications. Even on the same platform, various software produced by different software vendors often need to be integrated. Through Web Services, applications can use standard methods to “expose” functions and data for use by other applications.

XML Web services provide 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. B2B integration

B2B refers to Business to Business, as in businesses doing business with other businesses, merchant (generally refers to enterprise) to merchant e-commerce, that is, the exchange of products, services and information between enterprises through the Internet. In layman’s terms, it means that both the supply and demand sides of e-commerce transactions are merchants (or enterprises, companies), and they use Internet technology or various business network platforms to complete the process of business transactions.

Web Service is the key to successful B2B integration. Through Web Service, companies can simply “expose” key business applications to designated suppliers and customers. Web Service runs on the Internet and can be easily implemented anywhere in the world, and its operating costs are relatively low. Low. Web Service is only a key part of B2B integration, and many other parts are needed to achieve integration. The biggest advantage of using Web Service to implement B2B integration is that interoperability can be easily achieved. As long as the business logic is “exposed” and becomes a Web Service, any designated partner can call these business logic, regardless of what platform their system runs on or what development language they use. This greatly reduces the time and cost spent on B2B integration.

4. Software and data reuse

While Web Service allows code reuse, it can also reuse the data behind the code. Using Web Service, you no longer have to purchase and install software components from a third party as before, and then call these components from the application; you only need to directly call the remote Web Service. Another situation of software reuse is to integrate the functions of several applications and “expose” them through Web Service. You can easily integrate all these functions into your portal site and provide users with a unified , friendly interface. You can use the functions provided by third-party Web Services in your application, or you can provide your own application functions to others through Web Service. In both cases, the code and the data behind the code can be reused.

From the above discussion, it can be seen that Web Service is most useful when interoperating or remotely calling through the Web. However, there are also some situations where Web Service cannot bring any benefits at all. Web Service has the following Disadvantages:

1. Stand-alone application

Currently, businesses and individuals still use many desktop applications. Some of them only need to communicate with other programs on the machine. In this case, it is best not to use Web Service, just use the local API. COM is ideal for working in this situation because it is small and fast. The same goes for server software running on the same server. Of course, Web Service can also be used in these situations, but that would not only consume too much, but also not bring any benefits.

2. Some applications of LAN

In many applications, all programs use COM under the Windows platform and run on the same LAN. In these programs, using DCOM will be much more efficient than SOAP/HTTP. Similarly, if a .net program wants to connect to another .net program on the LAN, .net Remoting should be used. In fact, in .net Remoting, you can also specify to use SOAP/HTTP to make Web Service calls. However, it is better to make RPC calls directly through TCP, which is much more efficient.

Summary: Architecturally speaking, Web Service is roughly divided into 5 levels:

1. HTTP transport channel
2. XML data format
3. SOAP encapsulation format
4. WSDL description method
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 IIS architecture, so it is relatively easy to deploy (Dispose).

From an implementation perspective, firstly, WebService must inherit the class of the method exposed to the client from the base class System.Web.Services.WebService. Secondly, the exposed method must be preceded by [WebMethod] or [WebMethodAttribute].

The operating mechanism of WebService
First, the client sends the WSDL from the server to the WebService, and at the same time claims a proxy class (Proxy Class) on the client. This proxy class is responsible for Request and Response with the WebService server. When a data (XML format) is encapsulated into SOAP format When the data stream is sent to the server, a process object will be generated and the SOAP packet received by the Request will be parsed, and then the thing will be processed. After the processing is completed, the calculation result will be SOAP packaged, and then the packet will be used as a Response is sent to the client’s proxy class (Proxy Class). Similarly, this proxy class also parses the SOAP packet and performs subsequent operations. This is a running process of WebService.

3. Comparison between .NET Remoting and Web Service

1. .net remoting uses HttpChannel, which can use the various benefits of the Http protocol like WebService, such as transmitting through firewalls. But WebService is a cross-platform thing. Java and .Net can provide and reference each other’s WebService. .net remoting is limited to the .net platform.

2. .net remoting is stateful and tightly coupled; web service is stateless (because http is stateless) and loosely coupled; in general, remoting is suitable for local area networks and is good for performance and response efficiency. Strictly speaking, remoting and web service are not technologies corresponding to J2EE’s EJB. If you must compare, Then the .net remoting component deployed in COM + /MTS can correspond to EJB.

3. .net The performance of remoting on the LAN is definitely much better than that of web services. It uses tcp pipes to transmit data without distortion, thereby easing the work of serialization and deserialization. Of course When using WEB services, the way one computer stores 32-bit integers is different from the way another computer stores them, so an easy-to-understand format like XML is needed. Web services are executed by IIS, and .NET Remoting is highly scalable. HTTP channel and XML can be used to achieve part of the web services technology. Personally, I think web services can be regarded as a special case of .NET Remoting.

Conclusion

Whether it is Web Service or Microsoft.Net Remoting, it can be said to be broad and profound. The entire content of Web Service and Remoting is not what I can describe in this short article. As the question shows, it is a “brief discussion”. Criticisms and corrections are welcome!

Original address: http://www.cnblogs.com/DebugLZQ/archive/2012/07/30/2614815.html