ICE-NODEJS NODE.JS使用ICE进行分布式通信-环境搭建
ICE3.7目前并不是稳定版本,因此选择ICE3.6.4,编译器VS2015。
要注意,ICE3.6的代码和ICE3.7的代码不同。使用官方文档时,使用对应的版本。
一.ICE安装:
二.编写一个测试服务器,使用C++编写,开发环境VS2015。
安装插件,这可以方便开发。ICE BUILDERS IceBuilder.vsix https://zeroc.com/downloads/builders
建立一个C++控制台工程,之后选择Add ice builder to project。插件可以帮我们配置包含目录,编译ice文件,十分方便。
新建一个slice文件,Printer.ice。
定义接口如下
module Demo
{
interface Printer
{
void printString(string s);
};
};
之后插件会自动生成对应的.h,.cpp文件(编译器会报很多错误,这应该是个BUG,比较烦。留下cpp,h文件,从工程中移除ice文件,就没这些错误了。)
之后修改main函数,代码如下。
#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 <<"server:"<< s << endl;
}
int
main(int argc, char* argv[])
{
int status = 0;
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;
}
ICE程序运行时,需要DLL库。可以设置环境变量,也可以直接将DLL库拷贝到程序目录。
编译的程序版本不同,使用的DLL库也不同。对应关系见下 (https://doc.zeroc.com/display/Ice36/Using+the+Windows+Binary+Distribution#UsingtheWindowsBinaryDistribution-PATHEnvironmentVariable)
set ICE_HOME=C:\Program Files (x86)\ZeroC\Ice-3.6.4
我们编译的是vs2015 x86版本,因此C:\Program Files (x86)\ZeroC\Ice-3.6.4\bin\vc140目录下的库。带d的代表debug版本,不带d的代表release版本
测试程序,比较简单。只需要把ice36d.dll,iceutil36d.dll两个库。
三.编写nodejs客户端
1.首先安装ICE的JS包
npm install [email protected]
2.把ice文件(Printer.ice)编译出js版本代码,命令行输入
slice2js Printer.ice
得到Printer.js文件
3.编写client.js,代码如下
var Ice
= require("ice").Ice;
var Demo
= require("./Printer").Demo;
var ic;
Ice.Promise.try(
function()
{
ic = Ice.initialize();
var base
= ic.stringToProxy("SimplePrinter:default -p 10000");
return Demo.PrinterPrx.checkedCast(base).then(
function(printer)
{
return printer.printString("Hello
World!");
});
}
).finally(
function()
{
if(ic)
{
return ic.destroy();
}
}
).exception(
function(ex)
{
console.log(ex.toString());
process.exit(1);
});
打开C++的控制台程序,运行node.js
node client.js
就可以看到控制台上打印出
server:Hello World!
|