接第01部分,本节用来说明C#语言的代码实现。
使用slice2cs之后,会生成一个文件JustATest.cs,无论是Client还是Server都要包含这个文件。
首先是Server端:
1、新建一个Console项目,引用ICE程序集中的Ice.dll,项目中添加JustATest.cs文件。
2、新建一个类MyICETest,实现iIceTestDisp_接口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ice;
using com.neohope.ice.test;
namespace TestICEServer
{
class MyICETest : iIceTestDisp_
{
public override string SayHelloTo(string s, Current current__)
{
return "Hello " + s;
}
public override int Add(int a, int b, Current current__)
{
return a + b;
}
}
}
3、修改Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestICEServer
{
class Program
{
static void Main(string[] args)
{
Ice.Communicator ic = null;
//初使化
ic = Ice.Util.initialize(ref args);
//创建适配器,并指定监听端口
Ice.ObjectAdapter adapter = ic.createObjectAdapterWithEndpoints("NeoTestAdapter", "default -p 1900");
//绑定
Ice.Object obj = new MyICETest();
adapter.add(obj,Ice.Util.stringToIdentity("NeoICETest"));
//激活适配器
adapter.activate();
//持续监听,直到服务关闭
ic.waitForShutdown();
//清理
if (ic != null)
{
try
{
ic.destroy();
}
catch (Exception e)
{
}
}
}
}
}
4、编译运行
然后是Client端:
1、新建一个Console项目,引用ICE程序集中的Ice.dll,项目中添加JustATest.cs文件。
2、修改Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.neohope.ice.test;
//using JustATest;
namespace TestICE
{
class Program
{
static void Main(string[] args)
{
Ice.Communicator ic = null;
try
{
//初使化
ic = Ice.Util.initialize(ref args);
Ice.ObjectPrx obj = ic.stringToProxy("NeoICETest:default -p 1900");
//查找并获取代理接口
iIceTestPrx client = iIceTestPrxHelper.checkedCast(obj);
if (client == null)
{
throw new ApplicationException("Invalid proxy");
}
//调用服务端方法
Console.WriteLine(client.SayHelloTo("neohope"));
Console.WriteLine(client.Add(1, 2));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
//清理
if (ic != null)
{
try
{
ic.destroy();
}
catch (Exception e)
{
Console.Error.WriteLine(e);
}
}
}
}
}
}
3、编译运行
PS:
1、不要乱修改id,如果要修改,必须全部修改
2、我调整了包名,不调整也可以