一、什么是Hessian:
Hessian是一个轻量级的remoting onhttp工具,使用简单的方法提供了RMI的功能. 相比WebService,Hessian更简单、快捷。采用的是二进制RPC协议,因为采用的是二进制协议,所以它很适合于发送二进制数据,支持目前所有流行的开发平台。
二、Hessian的用途:
Hessian实现web服务。
三、资源:
Hessian官方网站下载http://hessian.caucho.com/
四、实例演示:
由于本人在实际项目中的情形是这样的:服务器端是Java程序,客户端是C#程序。之前采用的是WebService的技术进行数据传输。后来发现通过Hessian的方式来传输数据的话,效率要高很多。实例中服务端、客户端的程序都是采用C#开发的。开发环境:Visual Studio 2010,如下:
服务端:
新建一个VS的web项目,引用Hessiancsharp.dll (Hessian官方网站下载)。
新建一个实体类,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HessianService
{
public class Student
{
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public Student(string name, int age)
{
this.name = name;
this.age = age;
}
}
}
新建一个接口,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace HessianService
{
public interface IService
{
string Hello(string name); //返回字符串
Student GetStudent(); //返回实体对象
}
}
新建一个服务类,继承于IService接口,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using hessiancsharp.server;
namespace HessianService
{
public class Service : CHessianHandler, IService
{
public string Hello(string name)
{
return "Hello" + name;
}
public Student GetStudent()
{
Student s = new Student();
s.No = 214101;
s.Name = "lisi";
return s;
}
}
}
注意服务实现要继承CHessianHandler这个类,这个类继承实现了IHttpHandler。服务端的代码已经编写完成了,不过现在这个服务还不能向外提供服务,我们还要对它进行一下小小的配置。打开Web.config 在<System.web>中添加如下代码:
<webServices>
<protocols>
<remove name="HttpPost"/>
<remove name="HttpGet"/>
</protocols>
</webServices>
<httpHandlers>
<add verb="*" path="*.hessian" type="HessianService.Service, HessianService"/>
</httpHandlers>
到此为止,服务器的程序就已经写好了。
客户端:
新建控制台项目HessianConsole,然后将服务端定义的接口:IService和实体类:Student 复制到客户端。特别注意:名称空间也需要同服务器端的保持一样。
接下来修改Program.cs, 代码如下:
using hessiancsharp.client;
using HessianService;
class Program
{
static void Main(string[] args)
{
CHessianProxyFactory factory = new CHessianProxyFactory();
string url = "http://localhost:4225/HessianService.hessian"; //服务器端的地址
IService service = (IService)factory.Create(typeof(IService), url);
string result = service.Hello("你好!");
Console.WriteLine(result);
Student s = service.GetStudent();
Console.WriteLine(string.Format("Age={0}, Name={1}", s.Age, s.Name));
Console.Read();
}
}
到此为止,通过Hessian的方式在服务端与客户端传递数据的简单示例程序已经完成。