Java and c # Use hessian for communication,

Source: Internet
Author: User

Java and c # Use hessian for communication,

Introduction

Hessian home: http://hessian.caucho.com/

A simple example is to learn the hessian service: the server is Java and the client is C #.

First prepare C # and Java third-party class libraries: http://hessian.caucho.com/

Hssiancharp. dll

Hessian-4.0.37.jar

Hessian server (java)

Open eclipse to create a Dynamic Web Project, put the hessian-4.0.37.jar under lib, probably:

Create a communication interface IHello:

package hessian.test.server;import java.util.ArrayList;public interface IHello {    String sayHello(String msg);           void sayHello2(int bean);        void print(String msg);          HelloBean getData(HelloBean bean);        ArrayList<HelloBean> getBeanList();        ComplexData getComplexData();    }

An IHello interface implementation: HelloImpl. java

package hessian.test.server;import java.util.ArrayList;public class HelloImpl implements IHello{        public String sayHello(String msg){        return "Hello " + msg;    }        public void sayHello2(int bean){        System.out.println("Hello " + bean);    }        public void print(String msg){        System.out.println(msg);    }        public HelloBean getData(HelloBean bean){        HelloBean result = new HelloBean();        result.setName("lu xiaoxun a new name");        result.setAge(26);                System.out.print(bean.getName());        return result;    }        public ArrayList<HelloBean> getBeanList(){        ArrayList<HelloBean> beans = new ArrayList<HelloBean>();                HelloBean b1 = new HelloBean();        b1.setName("lu1");        b1.setAge(26);        beans.add(b1);                HelloBean b2 = new HelloBean();        b2.setName("lu2");        b2.setAge(27);        beans.add(b2);                return beans;    }        public ComplexData getComplexData(){        ComplexData data = new ComplexData();        ArrayList<HelloBean> beans = getBeanList();        data.setData(beans, beans.size());                return data;    }}

Defines the classes used for data transmission. Both classes must implement the Serializable interface:

HelloBean. java

package hessian.test.server;import java.io.Serializable;public class HelloBean implements Serializable {    private static final long serialVersionUID = 570423789882653763L;    private String name;        private int age;        public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }        public int getAge(){        return age;    }        public void setAge(int age){        this.age = age;    }    }

ComplexData. java

package hessian.test.server;import java.io.Serializable;import java.util.ArrayList;import java.util.HashMap;import java.util.Map;public class ComplexData implements Serializable{    private static final long serialVersionUID = 1L;    private ArrayList<HelloBean> helloBeans;        //private Map<String, HelloBean> helloBeanMap;        private int number;        public int getNumber(){        return number;    }        public ArrayList<HelloBean> getHelloBeans(){        return helloBeans;    }        public void setData(ArrayList<HelloBean> beans, int num){        this.number = num;        this.helloBeans = beans;//        helloBeanMap = new HashMap<String, HelloBean>();//        for (HelloBean helloBean : beans) {//            if(!helloBeanMap.containsKey(helloBean.getName()))//            {//                helloBeanMap.put(helloBean.getName(), helloBean);//            }//        }    }}

Web. xml content:

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"    id="WebApp_ID" version="3.0">    <display-name>hessian server</display-name>    <servlet>        <servlet-name>hessian</servlet-name>        <servlet-class>com.caucho.hessian.server.HessianServlet</servlet-class>        <init-param>            <param-name>service-class</param-name>            <param-value>hessian.test.server.HelloImpl</param-value>        </init-param>    </servlet>    <servlet-mapping>        <servlet-name>hessian</servlet-name>        <url-pattern>/hessian</url-pattern>    </servlet-mapping></web-app>

Hessian client (c #)

Define an IHello interface corresponding to the server: IHello. cs

    public interface IHello    {        String sayHello(String msg);        void sayHello2(int bean);        void print(String msg);        HelloBean getData(HelloBean bean);        HelloBean[] getBeanList();        ComplexData getComplexData();    }

Define the same communication data class as the server:

HelloBean. cs

Using System; using System. collections. generic; using System. linq; using System. text; namespace hessian. test. server {public class HelloBean {public String Name {set {name = value;} get {return name ;}} private String name; // The type and name must be the same as the public int Age {set {age = value;} get {return age ;}} private int age on the server; // The type and Name must be consistent with that on the server. public override String ToString () {return "name:" + Name + "Age:" + age ;}}}

ComplexData. cs:

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace hessian.test.server{    public class ComplexData    {        private HelloBean[] helloBeans;        //private Dictionary<String, HelloBean> helloBeanMap;        private int number;        public int GetNumber()        {            return number;        }        public HelloBean[] GetBeans()        {            return helloBeans;        }        //public Dictionary<String, HelloBean> GetBeansDic()        //{        //    return helloBeanMap;        //}    }}

Add Hessiancsharp. dll reference in the main project.

Test code:

Using System; using System. collections. generic; using System. linq; using System. text; using hessiancsharp. client; using hessian. test. server; namespace HessianClientTest {class Program {static void Main (string [] args) {string url = @ "http: // localhost: 8080/HessianServerTest/hessian "; CHessianProxyFactory factory = new CHessianProxyFactory (); IHello test = (IHello) factory. create (typeof (IHello), url); // Te St function Console. writeLine (test. sayHello ("lu"); // print the string test. sayHello2 (12); // print "Hello 12" test on the server console. print ("hessian"); // print "hessian" on the server console // Test Object HelloBean bean = new HelloBean (); // bean. setName ("lu xiaoxun"); bean. name = "luxiaoxun"; HelloBean result = test. getData (bean); Console. writeLine (result. name); Console. writeLine (result. age); Console. writeLine (result); // Test Obj Ect Array HelloBean [] beans = test. getBeanList (); if (beans! = Null) {foreach (HelloBean data in beans) {Console. writeLine (data. toString () ;}// Test complex data ComplexData complexData = test. getComplexData (); if (complexData! = Null) {Console. WriteLine ("Array number:" + complexData. GetNumber (); HelloBean [] comArray = complexData. GetBeans (); if (comArray! = Null) {foreach (HelloBean data in comArray) {Console. writeLine (data. toString () ;}}// Dictionary <String, HelloBean> helloBeanMap = complexData. getBeansDic (); // if (helloBeanMap! = Null) // {// foreach (String key in helloBeanMap. keys) // {// Console. writeLine (helloBeanMap [key]. getHelloBeanInfo (); //} Console. readKey ();}}}

Test results:

Note:

1. The namespace of the objects used by the server and the client for data transmission must be consistent.

The namespace of the IHello interface can be different from that of the client. However, the HelloBean and ComplexData used in IHello must be consistent in the namespace of the two HelloBean classes on the Java Server and C # client.

2. The fields of the class must be consistent.

The field names and Field Types of the classes used for data transmission must be consistent (the modifier types can be different ).

3. The server class must be serialized.

4. Try to use Basic Data Types

From the test above, we can see that there is no problem in passing basic types, there is no problem in passing common class objects, and there is no problem in passing the ArrayList (C # The client uses an Array ), however, a problem may occur when the HashMap Dictionary is passed. C # The use of Dictionary cannot be consistent. It may be caused by inconsistent implementation of the hash function. The specific reason is unknown.

 

Test code: HessianTest.rar

 


Comparison between java and C

On the Internet, c is the basis of java because c is the originator of advanced languages and the basis for learning any other advanced languages.
According to this idea, the assembly language is the basis of the C language, and the machine language is the basis of the assembly language ..
If you start from machine linguistics to java, I don't think you will ask questions on Baidu any more.

You have learned the course for any time you want to learn. Don't think too much about it. Go where your goal is. The goal is to learn java in java. The basic things can be supplemented later. First, you need to understand the java concept.
Try to do the same thing first.

Association between java and C Language

I feel very serious about your question, so let me say a few words.
1. Level 2 and Level 3 are not worth mentioning for computer majors, no matter how many points they earn. Computer experts focus on operating systems and compilers (automated machines, formal languages, and mathematical logic ). These courses can be deeply understood, even if there is no white learning. However, only a very small number of people really understand it. A large number of people cannot understand the subject or even master's degree.
2. "java programming ideas" is a good book and is recommended for reading.
3. In fact, all languages are similar. Compilation in many languages, Java, BASIC, Fortran, SQL, PHP, Perl, TCL ......, There are also a lot of scripts such as Bash, sed, and even some graphical languages, which can be used in the same project at the same time. It is very difficult to be proficient in every language. After all, you are still an undergraduate student.
4. The C language is the most basic and the most difficult choice. If you have mastered the C language, you should be close to or even surpass me. For example, if you see volatile, can you really understand its meaning? If not, it means that the C language is not getting started yet. You need to know that there are only dozens of keywords in the C language. If there is such a keyword, you don't know its meaning.
5. Java is a simple and practical language because it has seen that the C language is too complex. It can do a lot of things and is not as difficult to understand as C language. However, I personally think that it is best for computer majors to understand the C language or C ++ language, but the method of thinking about Java's surface objects must be understood. C language allows you to create object-oriented methods by yourself. After all, most of the later languages were implemented in C language at the beginning, including C ++, Java, PHP, and so on.
6. about girls. I think the computer industry is too tired, so it is very important to understand some conceptual things, and it is too little to really work. I have met a girl from a senior high school. But to be honest, girls are given extra points for the awards. This indicates that it is indeed difficult to reach the same level.

In short, the key to a language is not a syntax, but its thoughts. C language is a transparent language. You can estimate the compiled results to write the Operating System. Java is an object-oriented language, you can use a small amount of code to complete some tasks that are difficult to complete in the same amount of code in the C language, and this method is suitable for many people to cooperate.

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.