您的位置:首页 > 编程语言 > C语言/C++

ICE学习(二)-Ice编程 C++

2014-04-05 21:39 169 查看
本节介绍下如何用C++编写ICE程序,步骤和之前编程模型里介绍的是一样的。

这个程序很简单,是一个远程打印,客户端发一个字符串给服务器,服务器打印再发一个回复回来。

1.写Slice Definition

//Printer.ice
module Demo {
interface Printer {
void printString(string s);
};
};
2.为C++代码编译SliceDefinition

运行这条命令(使用VS2010配合ICE插件,可以自动在IDE中编译)

slice2cpp Printer.ice

slice2pp生成2个文件,Printer.h和Printer.cpp,之后的客户端和服务器将要用到它们。

3.编写服务器代码并编译

虽然下面的代码看起来很多,但大部分代码都是样板代码,基本不会改变。Ice提供了一个帮助类,把这些样板代码包装进去Ice::Application。

这段代码真正需要关心的就是定义PrinterI的那6行,加上定义一个PrinterI对象,并注册到adapter的那三行而已。

//Server.cpp 服务端源代码

//首先包含Ice.h,里面有Ice运行时的定义。

//还要包含printer.h包含我们接口的定义。

#include<Ice/Ice.h>

#include<Printer.h>

using namespacestd;

using namespaceDemo;

class PrinterI :public Printer {

public:

virtual void printString(const string&s, const Ice::Current&);

};

voidPrinterI::printString(const string& s, const Ice::Current&)

{

cout << s << endl;

}

//注意printString的第二个参数,这里实现可以不用理它,我们之后会讲它的作用。

int main(intargc, char* argv[])

{

//status用来表示程序退出的状态。

int status = 0;

// ic保存的是ice运行时的句柄。

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捕捉所有ICE运行时抛出的异常。它的意图是,运行时发生异常时,栈不会崩溃返回到main中打印错误信息。

catch (const Ice::Exception& e) {

cerr << e << endl;

status = 1;

}

//第2个catch 捕捉字符串常量。它的意图是,如果我们的代码出现致命错误,我们可以抛出一个带错误信息的字符串,返回到main中打印信息。

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;

}

4.编写客户端代码并编译

//Client.cpp 客户端代码

#include<Ice/Ice.h>

#include<Printer.h>

using namespacestd;

using namespaceDemo;

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("HelloWorld!");

} catch (const Ice::Exception& ex) {

cerr << ex << endl;

status = 1;

}catch (const char* msg) {

cerr << msg << endl;

status = 1;

}

if (ic)

ic->destroy();

return status;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: