Communication Mechanism in Java and integration with C/C APIs

Source: Internet
Author: User
Tags unpack

Background

The most annoying thing about the transformation and upgrade of old systems is cross-platform and cross-language. One of my friends recently specialized in. Net from Java-Because. Net CLR has a proven underlying hosting capability similar to the Java Virtual Machine Concept. It also provides good compatibility with desktop applications for Windows.

Recently, my personal projects are also faced with such demands. A middleware developed in C language is exposed to secondary development and plug-in applications through APIS. The demand for its applications is becoming increasingly complex, and it is moving away from the Unix management environment to BCS Management Based on JWS. A friend recommended me to use JNI, but this increased the Coupling Degree and made Java sleeping in JNI feel unstable. After recognizing the upper and lower layers of the system platform, the problem becomes clear: How to Implement interaction between Java and C under HTTP?

Ideas

I am familiar with Java. From the Java perspective, the communication methods between Java are as follows:

1. Access the dynamic resources (servlet) injected to the URL through URL, applet/JWS)

2. Access shared static resources through URL, applet/JWS (server regularly updates static resources)

3. Transmission of Simple objects through serialization and deserialization (for example, the Hessian framework of Resin provides this communication mode)

4. Using some toolsCodeGenerate and use web services to achieve interaction between the client and the server

In addition, RMI and socket programming can also be performed out of HTTP.

The problem is that the communication end is changed from Java to C/C ++. Therefore, solution 1 needs to define dynamic resources by CGI, and solution 3 is no longer applicable. The solutions include:

1. Access the dynamic resources (CGI) injected to the URL through URL, applet/JWS)

2. Access shared static resources through URL, applet/JWS (server regularly updates static resources)

3. Use some tools to generate code and use web services to implement interaction between the client and the server (××× this is the focus of our discussion ×××)

Solution

Now let's talk about the implementation methods in the communication methods 1 and 3 mentioned in the preceding 3. The implementation scheme 2 is flexible and requires everyone's imagination :)

For CGI:

First, CGI can be configured to run on various mainstream servers as backend scripts. You may be more familiar with servlet.

CGI can be written in script or C. After CGI is triggered, the system environment variables are used to obtain the input and output the results to the standard output after processing.

It can be seen that after the Web server receives a request from the HTTP protocol, it first obtains the Request Parameters and then sets them to the environment variables.

Based on the resolution of the accessed URL and the server's own configuration, find the CGI that serves the requestProgramAnd then execute the program.

After the program is executed, the environment variable obtains the parameters previously set by the server in the environment variable. After some complex logical operations, the output results are output to the standard.

This output is captured by the Web server and then transmitted back to the requesting client.

For more information and understanding about CGI, you can use Google to find the answer.

The above CGI method allows us to directly obtain the results, but the solution is more primitive and basic. Its Disadvantages include:

1. You need to develop the type transmission protocol, encapsulate and unseal it, otherwise only strings are supported;

2. We will not install one or implement a Web server for it to use the c api, which makes our underlying program stupid and redundant. We hope to have an ultra-thin server shell that can be opened through a port after the API is encapsulated.

For Web servcies

Based on the two shortcomings above, we can only pin our hopes on Web Services. Here I recommend gsoap, a well-known Web Services tool in C/C ++. You can goHttp://gsoap2.sourceforge.net/Download the tool.

With this tool, we can:

1. A Server Shell of stand-alone

2. A Web Services service automatically generated according to the API Program

3. a wsdl descriptor File

About the running mechanism of gsoap-based Web Services C server and Java client, and problems that need to be paid attention to when accessing gsoap web services through the Java client (I spent a day off to figure out), will be described below.

Next, let's talk about the gsoap framework. We will transform the old system written in C with gsoap and release it in the form of SOA.

As mentioned above, gsoap can be used to achieve the following three points:

1. A Server Shell of stand-alone

2. A Web Services service automatically generated according to the API Program

3. a wsdl descriptor File

The customer generates a SOAP request message based on the WSDL description. All Web services are placed behind the Web server. The SOAP requests generated by the customer are embedded in an http post request and sent to the web server. The Web server then forwards these requests to the Web Services request processor. The request processor parses the received SOAP request, calls Web Services, and then generates the corresponding soap response. After the Web server receives a soap response, it sends the information back to the client through HTTP response.

WSDL is a bridge between the client and the server in Web services. It describes the methods provided by objects. Soap helps us develop an officially recognized object encapsulation method. With WSDL, the client only cares about how to encapsulate the parameters with soap and obtain the results. The server only cares about how to unpack soap-> services-> packets. Gsoap can help us to unpack and package in the above process, while we can only focus on the implementation of services.

Let's get down to the truth. Here we will introduce the use of gsoap by taking a simple example of implementing the add, subtract, and open web services:

To publish this web service, we first need to define the service interface. This service may be an adapter of an existing service, so we define the header file.

Calc. h:

Typedef double XSD _ double;

Int NS _ add (XSD _ double A, XSD _ Double B, XSD _ double & result );

Int NS _ Sub (XSD _ double A, XSD _ Double B, XSD _ double & result );

Int NS _ SQRT (XSD _ double A, XSD _ double & result );

Note that we define double as XSD _ double (two underscores) to tell gsoap, the required SOAP format and WSDL format are based on document/literal instead of RPC/encoded. in order not to make things complex, I can only say that the Web Services tool that comes with java1.6 only supports the WSDL in the document/literal format, so we generate the WSDL in this format. For the choice between the two formats and their long story, you can refer to the followingArticle: Http://www.ibm.com/developerworks/webservices/library/ws-whichwsdl/

After compiling the header file, we can generate it using the tool provided by gsoap:

/Usr/lib/gsoap-2.7/bin/soapcpp2-S-2 Calc. h

For the generated main files, see the attachment.

Below we implement the functions defined in Calc. h:

// Contents of file "Calc. cpp ":

# Include "soaph. H"
# Include "ns. nsmap"
# Include
Int main ()
{
Struct soap;
Int M, s; // master and slave sockets

Soap_init (& soap );
M = soap_bind (& soap, "localhost", 9999,100 );
If (M <0)
Soap_print_fault (& soap, stderr );
Else
{
Fprintf (stderr, "socket connection successful: Master socket = % d \ n", M );
For (INT I = 1; I ++)
{
S = soap_accept (& soap );
If (S <0)
{
Soap_print_fault (& soap, stderr );
Break;
}
Fprintf (stderr, "% d: accepted connection from IP = % d. % d socket = % d", I,
(Soap. ip> 24) & 0xff, (soap. ip> 16) & 0xff, (soap. ip> 8) & 0xff, soap. IP & 0xff, S );
If (soap_serve (& soap )! = Soap_ OK) // process RPC Request

Soap_print_fault (& soap, stderr); // print error

Fprintf (stderr, "request served \ n ");
Soap_destroy (& soap); // clean up class instances

Soap_end (& soap); // clean up everything and close socket

}
}
Soap_done (& soap); // close master socket and detach Environment

}
// Implementation of the "add" remote method:

Int NS _ add (struct soap * soap, double A, double B, double & result)
{
Result = A + B;
Return soap_ OK;
}
// Implementation of the "sub" remote method:

Int NS _ Sub (struct soap * soap, double A, double B, double & result)
{
Result = A-B;
Return soap_ OK;
}
// Implementation of the "SQRT" remote method:

Int NS _ SQRT (struct soap * soap, double A, double & result)
{
If (A> = 0)
{
Result = SQRT ();
Return soap_ OK;
}
Else
{
Return soap_sender_fault (soap, "square root of negative value ",
"I can only compute the square root of a non-negative value ");
}
}

As mentioned above, we do not want to develop or apply a large Web server to publish Web Services-based C language APIs. The main function in our code implements a simple Web Server (based on socket ). This server uses APIs generated by gsoap to provide processing for soap.

Next, we will compile this embedded web server. during compilation, note that the stdsoap2.cpp file is copied from the gsoap package and is not automatically generated, after you download gsoap, you can find this file and its header file.

G ++-O calcserver Calc. cpp soapc. cpp soapserver. cpp stdsoap2.cpp

A c API provided in the form of web servers was born.

Run./calcserver on the server.

The following describes how to use the built-in JAVA tool to generate a client stub:

Copy the WSDL generated by gsoap to our Java Development Environment. Configure parameters to generate the client Web Services Code based on the ports and servers defined in the Web Services server:

/Usr/lib/JVM/jdk1.6.0 _ 03/bin/wsimport-extension-httpproxy: localhost: 9999-verbose ns. WSDL

After the environment is generated, add the environment to the eclipse compilation environment, and then create a new class in Eclipse:

Class test {
Public static void main (string ARGs []) {
Service = new service ();
Double H = service. getservice (). Sub (20000, 1 );
System. Out. println (h );
}
}

Expected result 19999.0 is displayed.

Summary:When Integrating JAVA and C platforms, we can have a variety of solutions, but first we should think of gsoap because it can accomplish tasks well.

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.