Enable WEB Services for C + + applications using XML-RPC

Source: Internet
Author: User
Tags representational state transfer

http://www.ibm.com/developerworks/cn/webservices/ws-xml-rpc/

Introduction

The Internet is now becoming more popular, and due to this and its inherent benefits, developers and IT departments are starting to move from complex C + + business and science applications to a WEB-based environment. The Simple Object Access Protocol, the protocol,soap of the representational state transfer,rest, and the XML Remote Procedure Call protocol (XML remotes) WEB service protocols such as Procedure CALL,XML-RPC can help integrate such legacy applications into the World Wide Web, for example, using XML-RPC as a mechanism to integrate existing C + + programs with other client technologies. This article will help you determine when to choose XML-RPC instead of using SOAP and REST. In addition, this article provides detailed step-by-steps guidance and sample code snippets for C + + integration using the Open source Xml-rpc library.

Why Choose XML-RPC?

The challenges of integration with C + + can be addressed in a number of ways. A typical approach to C + + code integration consists of a common object Request Broker Architecture (Common object Request broker Architecture,corba), a Distributed Component Object Model (distributed Component Object model,dcom), remote method invocation (Invocation,rmi) Internet ORB Interconnect Protocol (Internet Inter-ORB PROTOCOL,IIOP), and Java™ The native Interface (Java™native Interface,jni) is integrated.

Figure 1 shows three different applications developed using the existing C + + code integration (using the typical method mentioned above) in different programming languages (Java, VC + +, PL/1).

Figure 1. Current scenario with no XML-RPC

As you can see, the C + + code should expose the appropriate interfaces for each RMI/IIOP/JNI, CORBA, and DCOM client integration technology. This requires three development efforts, which clearly makes the process of deploying and managing such complex interfaces more difficult and cumbersome.

In these cases, XML-RPC is a better choice because it may help to streamline development, deployment, and management efforts.

About XML-RPC and REST

XML-RPC was Userland Software's Dave Winer in 1998. Visit Dave Winer's blog to learn about his initial thoughts on Xml-rpc.

REST was originally presented by Roy Thomas Fielding as part of his doctoral dissertation at the University of California, Irvine.

Figure 2. Using XML-RPC

Figure 2 shows how to use XML over HTTP to invoke a C + + program using remote procedure calls. Alternative techniques, such as SOAP and REST, can also be used for the same purpose. However, you will learn in the next section that there are some key differences between these technologies.

Comparison between SOAP, Xml-rpc, and REST

Although all three protocols support XML-RPC over HTTP, they differ from one another in C + +. Table 1 provides a detailed comparison of the various elements of these protocols.

Table 1. Comparison between SOAP, Xml-rpc, and REST
SOAP xml-rpc REST
Defined SOAP is a lightweight protocol for exchanging information in a decentralized, distributed environment. The protocol is based on XML and consists of three parts: envelopes, a set of encoding rules, and conventions used to represent remote procedure calls and responses. This is a remote procedure call that uses HTTP as the transport protocol and uses XML as the encoding method. XML-RPC is designed to be simple and allows the transmission, processing, and return of complex data structures at the same time. Representational state transfers are designed to reflect the behavioral image of a well-designed Web application: A network of web pages in which the user continues to use by selecting a link, and selecting the link will cause the next page to be transmitted to the user and rendered for use.
Goal SOAP implements a user-defined data type that extends the XML-RPC by providing the functionality of the specified receiver, message-specific processing control, and other functions. Very simple and well-organized extensible format. The HTML coder should be able to view the file containing the XML-RPC procedure call, understand what it is doing, and be able to modify it to work properly with just one or two attempts. This protocol is very easy to implement and can be quickly adjusted to run on other environments or other operating systems. The purpose of creating REST is to provide design patterns about how the web should work and as a guiding framework for Web standards and design Web services.
Supported data types Integer, Boolean, ASCII string, double-signed floating-point number, datetime, struct, array, byte array, enumeration, user-defined data type, polymorphic accessor Integer, Boolean, ASCII string, double-precision signed floating-point number, DateTime, structure, array. specific to the implementation. Commonly supported types are integers, Boolean, ASCII strings, double-precision signed floating-point numbers, DateTime, collections, lists, attributes.
Simplicity of Slightly more complicated than XML-RPC. Easy to understand and develop Implementation-specific
Stability Standard accepted by the consortium Not standard Architecture Reference. No standard required
Interoperability Cannot interoperate with REST/XML-RPC Cannot interoperate with Rest/soap Cannot interoperate with SOAP/XML-RPC
Tools Many major companies, including IBM and Microsoft, have started to support SOAP in their tools. The tool is still under development. And there are not many tools to support it.
Customization capabilities Highly customizable, independent of data type and protocol restrictions Lightweight, only works on HTTP, with limited data type support only works on HTTP
Library There are many open source libraries available. There are many open source libraries available. will be explained in the following section There are not many implementation libraries available
Table 2. Various XML-RPC implementations of C + +
Library and package names Description
Pdel The Packet Design Embedded Library is a C repository, where the XML-RPC implementation of the client and server is included through the HTTP_XML_SEND_XMLRPC and Http_servlet_xmlrpc methods. These functions help to send custom XML data over the HTTP transport protocol. This package also contains many other features other than XML-RPC.
Xmlrpc++ This is the C + + implementation of XML-RPC. It provides a simple server and client. By using object-oriented technology, we can integrate these servers and client classes and implement our own XML-RPC servers to expose business functions as services. In this article, our example implementation and related examples will use this library.
Xmlrpc-c This is a C implementation that can be used by C and C + + applications to expose these methods as services. A Abyss Web server is included in this package. To expose the C + + method, we can write a C-style wrapper for the required C + + method, and then use this library to expose this method.
Installing the Xml-rpc++ Library

The first step in enabling XML-RPC for a C + + program is to download and install the XML-RPC Library implementation. Provides a variety of implementations for C + + programs. You can get a link to more implementations in the Resources section.

Our sample program will be implemented using xmplrpc++. For more information on downloading and installing this implementation to Linux, AIX, 32-bit Windows platforms, and other similar platforms, see the Resources section. Our example implementation will be based on the Red Hat 9 platform, using the xml-rpc++ 0.7 library.

Sample C + + Applications

The sample application here is a simple addition of two integers, and a user-defined class named "Operations" will be used. Listing 1 shows the code snippet for the operations class.

Did you know that?

You can use Eclipse as the IDE for developing c/cpp applications. For more information, please visit the Eclipse CDT.

Listing 1. Operations
Class Operations {public:   int Add ();   Operations (int i, int j);p rivate:   int op1;//operand 1   int Op2;//operand 2};

The constructor for the class accepts two integer arguments and sets them to private variables OP1 and OP2, respectively. The Add method for this class is shown in Listing 2. This method is to be used as a method of exposing the XML-RPC service.

Listing 2. Operations.cpp
int Operations::add () {        std::cout << "Sum of" <<op1<< "+" <<op2<< "=" <<op1+op2& lt;<std::endl;        Return (OP1 + OP2);}

Back to top of page

Components of the XML-RPC library

In this section, we will use a class diagram to illustrate the various components of the XML-RPC library and how it connects to the operations class on our server side through the interface.

Figure 3. Class diagrams for XML-RPC libraries and sample applications

Table 3 provides a detailed description of each class.

Table 3. Class Details
class name Use
Operations The Add method to expose is implemented in this class
Add Call the wrapper class for the Add method of operations. This class is also inherited from Myxmlrpcservermethod
Myxmlrpcservermethod This class inherits from the Xmlrpcservermethod class of the XML-RPC library. The execute of the class is overwritten by inheritance in the Add class.
Xmlrpcservermethod Each method that needs to be registered with the server must inherit from the class through the Myxmlrpcservermethod class and implement its own Execute method. This execute method will be the wrapper for exposing the actual service. When the server receives the XML-RPC call, the Execute method of the wrapper class is triggered directly. In our example, add will be the wrapper class, and its Execute method will be called when the "ADD" service is called from the client.
Myxmlrpcserver The class has two important private variables
  1. Pm_servermethods: A list of pointers to myxmlrpcservermethods registered in the server.
  2. Pm_xmlrpcserver: Used to set the server IP, port, and other properties.

Three important methods
  1. Class constructor: Initializes the server object with the ip/port details and binds it.
  2. Pm_registermethods: Creates a pointer object to the Add class and adds it to the list pm_servermethods.
  3. Packaging of work methods in the Run:xmlrpcserver class
Xmlrpcserver This class is the XML-RPC server class that creates the server object. This class has the following two important methods
  1. Bindandlisten (port): binding and listening on a specific port specified
  2. Work (...) : Start the server

Listing 3 shows the code for each of the. cpp files for each class in the previous table. Since Xmlrpcserver and Xmlrpcservermethod are implemented in the XML-RPC library, we will focus on the remaining four classes.

Listing 3. MyXmlRpcServer.cpp
#include "MyXmlRpcServer.h" using namespace Xmlrpc;using namespace Std;myxmlrpcserver::myxmlrpcserver () {//call Register Methodspm_registermethods ();//set port bind and Listenint port = 8085;pm_xmlrpcserver.bindandlisten (port); STD ::cout<< "Xmlrpcsever running in Port" <<PORT<<STD::ENDL;} Voidmyxmlrpcserver::p m_registermethods () {        add* a=new Add (&pm_xmlrpcserver);        Myxmlrpcservermethod *p=a;        Pm_servermethods.push_back (P); }voidmyxmlrpcserver::run () {        pm_xmlrpcserver.work (-1);}
Listing 4. MyXmlRpcServer.h
#include <iostream> #include "myXmlRpcServerMethods.h" #include "XmlRpc.h" class Myxmlrpcserver {public:        Myxmlrpcserver ();        void Run ();p rivate:         void Pm_registermethods ();        Xmlrpc::xmlrpcserver Pm_xmlrpcserver;        std::list< myxmlrpcservermethod* > Pm_servermethods;};

Listing 5 and listing 6 show the code for registering a method with the class of XmlRpc Server (provided as part of the XML-RPC library).

Listing 5. MyXmlRpcServerMethods.cpp
#include <iostream> #include "myXmlRpcServer.h" #include "operations.h" using namespace std; Add::add (xmlrpcserver* s): Myxmlrpcservermethod ("Add", s) {}; Void Add::execute (Xmlrpcvalue & params, xmlrpcvalue& result) {Operations A (10,12); try     {      cout << Inside add::execute method\n ";      result = A.add ();    }  catch (Std::exception & stde)    {      throw xmlrpcexception (Stde.what ());}    }
Listing 6. MyXmlRpcServerMethods.h
Class Myxmlrpcservermethod:public Xmlrpcservermethod{public:  myxmlrpcservermethod   (const char *name, Xmlrpcserver * Server): Xmlrpcservermethod (name, server) {}   virtual void execute (xmlrpcvalue & params, xmlrpcvalue& result) {assert (0);}}; Class Add:public Myxmlrpcservermethod{public:   Add (xmlrpcserver* s);    virtual void execute (xmlrpcvalue & params, xmlrpcvalue& result);};
Server drivers

Server-side entry points are server drivers. The Myxmlrpcserver object is instantiated from here and the run () method is called, which eventually starts the server.

Listing 7. MyServerDriver.cpp
#include <iostream> #include "myXmlRpcServer.h" int main (int argc, char* argv[]) {        myxmlrpcserver Geeboombaa;        std::cout<< "About to run the server\n";        Geeboombaa.run ();        return 0;}

Back to top of page

Start the server

In order to compile the code, remember to include the (Xml_rpc_install_dir)/src and (Xml_rpc_install_dir)/include directories. For links, please include the LIBXMLRPC.A library. After the code has been successfully compiled and linked, an executable file is obtained that is the XML-RPC server. In our example implementation, the server will run on localhost and listen on port 8085. This setting is hard-coded in the MyXmlRpcServer.cpp file. You can also have the program read the configuration file, or pass this as a parameter to the program from a command-line prompt. Run successfully compiled and linked to the resulting A.out program to start the server.

Back to top of page

Sample Client

The sample client should instantiate an object from the Xmlrpcclient class provided by the XML-RPC library. "Execute (...)" For this class Will actually accept three parameters:

    1. Method name, const char* type
    2. Port number, const int type
    3. An optional URL string to send as a URI in the HTTP GET header

Listing 8 shows a sample client that will execute "add (...)" method, and outputs the results on the client.

Listing 8. SampleClient.cpp
#include <iostream> #include "XmlRpc.h" using namespace Xmlrpc;int main (int argc, char* argv[]) {        const char * Server = "localhost";        const int port = 8085;        const char *uri = NULL;        Xmlrpcvalue args, res;        Xmlrpcclient C (server, port, URI);        C.execute ("Add", args, res);        std::cout<< "result is" <<RES<<STD::ENDL;}

Back to top of page

Conclusion

Xml-rpc is a simple and powerful lightweight messaging protocol that supports XML-based communication across heterogeneous platforms. The inherent simplicity of this standard is very powerful and practical in integrating legacy applications with enterprise. Because each XML-RPC implementation is open source, this technology is becoming more and more popular in the area of enterprise application integration. With the advent of more and more mature xml-rpc tools, we can foresee that in the near future, this technology will become the "fact" standard for internal integration of enterprises.

Reference Learning
    • You can refer to the original English text on the DeveloperWorks global site in this article.
    • Learn more about the XML-RPC standard.
    • View a list of XML-RPC implementations for various programming languages.
    • Read the SOAP specification.
    • Xfront provides more information about XML.
    • View the comparison results for XML-RPC and SOAP.
    • Compare the performance differences between XML-RPC and SOAP.

Enable WEB Services for C + + applications using XML-RPC

Related Article

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.