什么是ICE
- ICE(Internet Communications Engine)是一种面向对象的高性能中间件平台,主要用于网络通讯。
- 使用ICE能使得php(c++、java、python)与java(c++、.net、python)等进行交互。
部署ICE开发环境
- 下载ice的资源库
wget http://www.zeroc.com/download/Ice/3.4/rhel5/zeroc-ice.repo
- 编辑repo
[zeroc-ice]
name=Ice 3.4 for Red Hat Enterprise Linux releasever−basearch
baseurl=http://www.zeroc.com/download/Ice/3.4/rhel5/$basearch
enabled=1
gpgcheck=1
gpgkey=http://www.zeroc.com/download/RPM-GPG-KEY-zeroc-release
- 使用yum安装
yum install ice* db46* mcpp-devel
代码开发
- 服务端:cpp+centos
- 客户端:php+centos
服务端
- 创建Printer.ice:该文件是ICE的slice文件,其中定义了服务的对象和接口
module Demo{
interface Printer{
void printString(string s);
}
}
- 创建Pritner.h和Printer.cpp
slice2cpp Printer.ice
- 创建Server.cpp
#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 << "Hello World" << 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;
}
- 编译
g++ -I . -o server server.cpp Printer.cpp -lIce -pthread
# 参数详解
# -I .: 编译时引入当前目录下的cpp#文件
# -o:不生成.o文件
# server:生成的程序名
# -lIce:需要支持的ice库
# -pthread:需要支持的pthread库
- 执行server
./server
客户端
- 创建Printer.php
slice2php Printer.ice
- 创建Client.php
<?php
error_reporting(E_ALL);
require 'Ice.php';
require 'Printer.php';
$ic = null;
try{
$ic = Ice_initialize();
$base = $ic->stringToProxy('SimplePrinter:default -p 10000');
$printer = Demo_PrinterPrxHelper::checkedCast($base);
if (!$printer) throw new RuntimeException('Invalid proxy');
$printer->printString("Hello World!");
} catch (Exception $ex) {
echo $ex;
}
if($ic) {
try{
$ic->destroy();
}catch(Exception $ex) {
echo $ex;
}
}
- 运行Client.php
现象
运行通过后,会在服务端打印Hello World的字符串
总结
这里只是初略的了解尝试了ice编译的客户端和服务端,完成了客户端和服务端的通信。