Ice簡介: 編程
Ice (Internet Communications Engine),是一種面向對象的中間件平臺,既然是平臺,那就意味着ice有本身的API和庫用與編寫Client/Server程序。Ice編寫的程序能夠在不一樣的操做系統和不一樣的編程語言環境下運行,由於客戶端/服務端程序能夠用不一樣的編程語言實現出來。並且還能利用不一樣的網絡技術進行傳輸交流。 網絡
Ice編程時,你只要考慮應用程序的邏輯結構便可,那些諸如網絡鏈接的開啓及網絡間的數據傳送等等這些細節,你大可沒必要考慮過多,你只要考慮你所要編寫的整個應用程序的邏輯層。 編程語言
下面用C++來實現一個Hello world的demo: spa
(這個demo的編譯成功得有個很大的前提條件的:Ice平臺的搭建及對Visual Studio 2008相應的環境變量的配置,這兩個東西的成功搭建是有點麻煩的。) 操作系統
首先,用slice定義一個以.ice爲後綴的文件Printer.ice 命令行
module Demo{ debug
interface Printer{ server
void printerString(string s); 中間件
}; 對象
};
在cmd命令行下,經過slice2cpp進行對Printer.ice的編譯,而後會在該ice所在文件夾裏神奇的產生出相應的printer.h和printer.cpp。以下圖:
接着在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以後都希冀其能正常運行,卻每一次都事與願違,焦慮的心靈總在這樣的過程當中反覆摺疊着,咱們就這樣成長了。
加油。