因爲公司需要讓我瞭解一下ICE,所以寫下來我的一些瞭解情況供分享。因爲接觸不久所以寫的比較淺顯,請多包涵。
ICE是什麼
ICE is a modern object-oriented toolkit that enables you to build distributed applications with minimal effort:
配置VS2013開發環境
HelloWorld
module Demo {
interface Printer {
void printString(string s);
};
};
2. VS2013 ICE add-in 安裝後,可在VS TOOLS -> Ice Configuration 中勾選Enable Ice Builder。#include <iostream>
#include <Ice/Ice.h>
#include <Printer.h>
using namespace std;
using namespace Demo;
class PrinterI : public Printer // the servant
{
public:
virtual void printString(const string &s, const Ice::Current ¤t);
};
void PrinterI::printString(const string &s, const Ice::Current ¤t)
{
cout << "In function " << __FUNCTION__ << " with string: " << s << endl;
}
int main(int arc, char **argv)
{
int status = 0;
Ice::CommunicatorPtr ic;
try {
ic = Ice::initialize(arc, argv);
Ice::ObjectAdapterPtr adapter = ic->createObjectAdapterWithEndpoints("SimplePrinterAdapter",
"default -p 10000:default -p 10001");
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 (NULL != ic) {
try {
ic->destroy();
} catch (const Ice::Exception &e) {
cerr << e << endl;
status = 1;
}
}
return status;
}
4. 添加Client 端調用 printString()的代碼:#include <iostream>
#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:default -p 10001");
PrinterPrx printer = PrinterPrx::checkedCast(base);
// PrinterPrx printer = PrinterPrx::uncheckedCast(base->ice_connectionCached(false));
if (!printer)
throw "Invalid proxy";
printer->printString("Hello, World!");
} catch (const Ice::Exception &e) {
cerr << e << endl;
status = 1;
} catch (const char *msg) {
cerr << msg << endl;
status = 1;
}
if (NULL != ic)
ic->destroy();
return status;
}
5. 編譯運行,運氣好的話調用客戶端的代碼後在服務器端就可以看到 Hello, World了。