先从ZEROC网站上下载ice 3.4.2 for windows,这个版本要求安装dotnet,安装完ice后,要设置一下系统变量
并下载python2.6.6,安装.
设置环境变量
ICE_HOME=C:\Program Files\ZeroC\Ice-3.4.2
ICEPY_HOME=C:\Program Files\ZeroC\Ice-3.4.2
PATH+=%ICE_HOME%/bin; 将ICE的路径添加到path里
PYTHON_HOME=C:\Python26\
PYTHONPATH=%ICE_HOME%/bin;%ICE_HOME%/python; //这里是python自己会搜索的路径.将ice的路径添加到里面.
以下是显示路径的python脚本
import sys,os
print(os.sys.path)
raw_input('\npath show over')
如果能正确显示下面的路径,就能正常的搜索到ICE的路径
Demo.ice
module Demo {
interface Printer {
void printString(string s);
};
};
Server.py
服务端代码,动态调用编译ICE文件.
#coding:utf-8
import sys,traceback,Ice,os
ice_command="-I\'"+os.getenv('ICE_ROOT')+"/slice\' ./Demo.ice"
Ice.loadSlice(ice_command)
import Demo
class PrinterI(Demo.Printer):
def printString(self, s, current=None):
print s
status = 0
ic = None
try:
ic = Ice.initialize(sys.argv)
adapter = ic.createObjectAdapterWithEndpoints("SimplePrinterAdapter", "default -p 10000")
object = PrinterI()
adapter.add(object, ic.stringToIdentity("SimplePrinter"))
adapter.activate()
ic.waitForShutdown()
except:
traceback.print_exc()
status = 1
if ic:
try:
ic.destroy()
except:
traceback.print_exc()
status = 1
client.py
测试客户端代码:
#coding:utf-8
import sys,traceback,Ice,os
ice_command="-I\'"+os.getenv('ICE_ROOT')+"/slice\' ./Demo.ice"
Ice.loadSlice(ice_command)
import Demo
status = 0
ic = None
try:
ic = Ice.initialize(sys.argv)
"""
The proxy returned by stringToProxy is of type Ice::ObjectPrx, which is at the root of the inheritance tree for interfaces and classes.
stringToProxy返回了一个Ice::ObjectPrx对象,这个在继承树中是接口和类的根对象
"""
base = ic.stringToProxy("SimplePrinter:default -p 10000")
"""
But to actually talk to our printer, we need a proxy for a Demo::Printer interface, not an Object interface. To do this, we need to do a down-cast by calling Demo.PrinterPrx.checkedCast.
但是,实际上我们需要的是一个Demo::Printer接口,不是一个Object的接口,因此我们需要向下转型.
A checked cast sends a message to the server, effectively asking "is this a proxy for a Demo::Printer interface?" If so, the call returns a proxy of type Demo.PrinterPrx; otherwise, if the proxy denotes an interface of some other type, the call returns None.
checkedCast向服务器发送消息,询问"这是一个Demo::Printer的代理吗?"
如果是,返回一个Demo.PrinterPrx
否则,这个一个其他类型的代理,该调用返回None
"""
printer = Demo.PrinterPrx.checkedCast(base)
if not printer:
raise RuntimeError("Invalid proxy")
printer.printString("Hello World!")
except:
traceback.print_exc()
status = 1
if ic:
# Clean up
try:
ic.destroy()
except:
traceback.print_exc()
status = 1
运行通过.OK.