Ice “Hello World”的实现

Ice简介:

Ice (Internet Communications Engine),是一种面向对象的中间件平台,既然是平台,那就意味着ice有自己的API和库用与编写Client/Server程序。Ice编写的程序可以在不同的操作系统和不同的编程语言环境下运行,因为客户端/服务端程序可以用不同的编程语言实现出来。而且还能利用不同的网络技术进行传输交流。

Ice编程时,你只要考虑应用程序的逻辑结构即可,那些诸如网络连接的开启及网络间的数据传送等等这些细节,你大可不必考虑过多,你只要考虑你所要编写的整个应用程序的逻辑层。

下面用C++来实现一个Hello world的demo:

(这个demo的编译成功得有个很大的前提条件的:Ice平台的搭建及对Visual Studio 2008相应的环境变量的配置,这两个东西的成功搭建是有点麻烦的。

首先,用slice定义一个以.ice为后缀的文件Printer.ice

module Demo{

    interface Printer{

       void printerString(string s);     

};

};

在cmd命令行下,通过slice2cpp进行对Printer.ice的编译,然后会在该ice所在文件夹里神奇的产生出相应的printer.h和printer.cpp。如下图:

Ice “Hello World”的实现

接着在Visual Studio 2008里创建工程:

1,Server端的创建:

File ->new ->Project -> win32 ->win32 console project

输入工程名:Server,OK后进入下一步,勾上empty project,最后finish。这样就建立了一个空工程了。

在所建的solution里,对header file 右键Add ->existing item 进入printer.ice所在文件夹里,将printer.h并入。同理可将printer.cpp也并入到source file内。再在source file 内Add ->New item, 创建一个cpp文件,命名为PrinterServer。在printerServer里写下如下server端代码:

#include <Ice/Ice.h>
#include "Printer.h"


using namespace std;
using namespace Demo;


class PrinterI : public Printer {
public:
virtual void printString(const string& s, const Ice::Current&);
};


void PrinterI::printString(const string &s, const Ice::Current &)
{
cout<< s << endl;
}


int
main( int argc, char* argv[])
{
int status;
Ice::CommunicatorPtr ic;
try
{
ic = Ice::initialize(argc ,argv);
Ice::ObjectAdapterPtr adapter = 
ic->createObjectAdapterWithEndpoints("SimplePrinterAdapter","default -p 10000");
Ice::ObjectPtr object = new PrinterI;
adapter->add(object, ic->stringToIdentity("SimplePrinter"));
adapter->activate();
ic->waitForShutdown();
}
catch (const Ice::Exception& e)
{
cerr << e <<endl;
status = 1;
}
catch (const char* msg)
{
cerr<< msg<<endl;
status = 1;
}
if (ic)
{
try
{
ic->destroy();
}catch(const Ice::Exception& e){
cerr << e << endl;
status = 1;
}
}
return status;
}
编译,成功。

2,Client端的创建:

client端的创建和Server端的创建大致类似。只是最后一个cpp文件命名为PrinterClient而已,PrinterClient.cpp的代码为:

#include<Ice/Ice.h>
#include<Printer.h>


using namespace std;
using namespace Demo;


int
main(int argc, char* argv[])
{
int status = 0;
Ice::CommunicatorPtr ic;
try
{
ic = Ice::initialize(argc,argv);
Ice::ObjectPrx base = ic->stringToProxy("SimplePrinter: default -p 10000");
PrinterPrx Printer = PrinterPrx::checkedCast(base);
if (!Printer)
throw "Invalid proxy";
Printer->printString("Hello World");
Printer->printString("Bonjour,tout le monde");
}
catch (const Ice::Exception& e)
{
cerr<< e << endl;
status = 1;
}
catch (const char* msg)
{
cerr<< msg << endl;
status = 1;
}
if (ic)
{
ic->destroy();
}
return status;
}
编译,成功。

server程序和client程序的成功编译之后,运行顺序为:先运行server端,再开启client端。

总结:对这个hello world的最终成功实现,最大的挑战是visual Studio 2008 环境的配置,而对所写程序进行编译的过程是很艰辛的、很恼人的,每一次的debug之后都希冀其能正常运行,却每一次都事与愿违,焦虑的心灵总在这样的过程中反复折叠着,我们就这样成长了。

加油。

转载于:https://my.oschina.net/u/226310/blog/84410