使用Windows 10环境,VS2019进行ICE用例开发
用例结构:客户端和服务端
关键技术:集成ICE环境,可以创建ice文件并自动生成对应的cs文件
1.环境安装
ICE Build插件安装。安装以后,就可以在项目中插入ice文件
2.代码实现
创建两个控制台程序(Client和Server),基于.Net FrameWork 4.6.1平台。
分别在Nuget中进行引用
然后,创建ICE文件,文件内容如下
#pragma oncemodule Demo
{class People{string name;int age;};interface Hello{void sayHello(People people);People GetPeople(People people);}
}
接着分别生成项目。就会自动生成generated文件夹
然后实现服务端服务
namespace Server
{public class PrinterI : Demo.HelloDisp_{public override People GetPeople(People people, Current current = null){return people;}public override void sayHello(People people, Current current = null){Console.WriteLine(people.name+"今年已经"+people.age+"岁啦!");}}
}
服务端启动代码
class Program{static void Main(string[] args){try{using (Ice.Communicator communicator = Ice.Util.initialize()){var adapter =communicator.createObjectAdapterWithEndpoints("SimplePrinterAdapter", "default -h localhost -p 10000");adapter.add(new PrinterI(), Ice.Util.stringToIdentity("SimplePrinter"));adapter.activate();Console.WriteLine("启动成功");communicator.waitForShutdown();Console.ReadLine();}}catch (Exception er){Console.Error.WriteLine(er);return;}}}
最后在客户端进行调用;
class Program{static void Main(string[] args){try{using (Ice.Communicator communicator = Ice.Util.initialize()){var obj = communicator.stringToProxy("SimplePrinter:default -h localhost -p 10000");var printer = HelloPrxHelper.checkedCast(obj);if (printer == null){throw new ApplicationException("Invalid proxy");}People people = new People() { Name = "小王", Age = 99 , Sex = "nv"};printer.sayHello(people);var res = printer.GetPeople(people);Console.WriteLine(res.Name+"--"+ res.Address+"--"+ res.Sex);Console.ReadLine();}}catch (Exception ex){Console.Error.WriteLine(ex.Message);return;}}}
小伙伴可能已经发现,客户端的People对象和ice文件中定义的People对象不一样,实际上,在客户端本地新建文件使用部分类定义的形式对自动生成的People对象进行了扩充实验。
public partial class People : IPeople{public int Age { get => this.age; set => this.age = value; }public string Address { get => this.name; }public string Name { get => this.name; set => this.name = value; }string sex;public string Sex { get => this.sex; set => this.sex = value; }}public interface IPeople{int Age { get; set; }string Name { get; set; }string Address { get; }}
那么扩充有什么作用?扩充People对象,可以满足客户端实现更加灵活的业务,不必要和服务端的People定义完全一致,可以正常通讯的前提是,客户端和服务端都是使用相同的ice文件生成的,并且客户端扩充的People对象需要和服务端存在相同名称的成员。(允许客户端和服务端相同成员的访问级别不一致)
允许通信的原因是?ICE无法识别客户端的这种改变?从侧面验证了Ice运行过程中,对对象的赋值是按照字段或者属性名称的,不是整体序列化?
附官方用例:Writing an Ice Application with C-Sharp - Icehttps://doc.zeroc.com/ice/3.7/hello-world-application/writing-an-ice-application-with-c-sharp