日期:2013-04-10  浏览次数:20429 次

Ice是一种优秀的分布式网络中间件,比起Corba好上许多,也更简洁。优点我在这里也不便多说了,有专文介绍,也不是今天的主题。有兴趣的可以查一下,《程序员》杂志好像有专题。
下面主要介绍一下怎样使用C#编写基于Ice的网络应用程序。
环境:Windows Server 2003 Enterprise, Visual Studio.NET 2003(.NET Framework 1.1)
先到http://www.zeroc.com/download.html下载Ice的安装包,Windows下用msi的。为方便起见,我下载的是VS.NET2003的专用包。如下:


注意:Ice-1.5.1-VC71.msi 安装包是必需的。 安装完毕后,将安装目录下的bin目录加入环境变量的Path路径,然后就可以在VS.NET中开发Ice应用了。

首先,我们编写一个Slice定义文件(相当于Corba里面的idl文件)。文件内容很简单,因为我们要从一个“Hello World”程序开始。
命名为Printer.ice:
interface Printer
{
void printString(string s);
};
用下面的命令编译:slice2cs.exe Printer.ice(如果找不到命令,表示环境变量没有设置成功,可以使用bin目录的全路径)
这条命令会在当前目录下产生Printer.cs文件:


恭喜你,初战告捷!继续加油!
我用VS.NET建了一个空的解决方案IceTest,然后添加了一个空的项目IceTest,加入Printer.cs文件,最后建立Server.cs文件(不用说你也猜到了,现在是编写服务端)。文件目录如下:



在Server.cs中添加如下代码:

using System;

namespace IceTest
{
/**//// <summary>
/// Summary description for Server.
/// </summary>
public class Server
{
public Server()
{
//
// TODO: Add constructor logic here
//
}

public static void Main(string[] args)
{
int status = 0;
Ice.Communicator ic = null;
try
{
ic = Ice.Util.initialize(ref args);
Ice.ObjectAdapter adapter
= ic.createObjectAdapterWithEndpoints(
"SimplePrinterAdapter", "default -p 10000");
Ice.Object obj = new PrinterI();
adapter.add(
obj,
Ice.Util.stringToIdentity("SimplePrinter"));
adapter.activate();
ic.waitForShutdown();
}
catch (Exception e)
{
Console.Error.WriteLine(e);
status = 1;
}
finally
{
if (ic != null)
ic.destroy();
}
Environment.Exit(status);
}
}

public class PrinterI : _PrinterDisp
{
public override void printString(string s, Ice.Current current)
{
Console.WriteLine(s);
}
}
}
前面的代码都是例行公事,public class PrinterI : _PrinterDisp的代码才是我们需要的(简单吧!)
按照同样的方法,我们建立IceClientTest项目,先添加Printer.cs文件,然后编写Cient.cs文件,具体内容如下:

using System;

namespace IceClientTest
{
/**//// <summary>
/// Summary description for Client.
/// </summary>
public class Client
{
public Client()
{
//
// TODO: Add constructor logic here
//
}

public static void Main(string[] args)
{
int status = 0;
Ice.Communicator ic = null;
try
{
ic = Ice.Util.initialize(ref args);
Ice.ObjectPrx obj = ic.stringToProxy(
"SimplePrinter:default -p 10000");
PrinterPrx printer
= PrinterPrxHelper.checkedCast(obj);
if (printer == null)
throw new ApplicationException("Invalid proxy");
printer.printString("Hello World!");
}
catch (Exception e)
{
Console.Error.WriteLine(e);
status = 1;
}
finally
{
if (ic != null)