本篇介绍如何用IceGrid建立python多机通信,传递比较复杂的参数
Ice代码:Demo.ice
#ifndef TOS_ICE_COMMON
#define TOS_ICE_COMMON module demo
{
class EventArgs
{
string source;
string occurTime;
}; struct Point
{
int x;
int y;
}; class pointEventArgs extends EventArgs
{
Point pt;
}; interface PointEvent
{
["amd","ami"] idempotent void OnNewPointEvent(pointEventArgs args);
}
}; #endif
1.python安装zeroC Ice:
pip install zeroc-ice
或者参照:https://blog.****.net/qq_37556007/article/details/80843541
2.对Ice文件进行切片
slice2py Demo.ice
得到Demo_ice.py
3.编写客户端
import Demo_ice
import Ice
import sys
import time class Client:
def __init__(self):
self.point = Demo_ice._M_demo.Point(x=10, y=20)
self.event = Demo_ice._M_demo.pointEventArgs(source='client', occurTime=time.time().__str__(), pt=self.point) with Ice.initialize(sys.argv) as communicator:
base = communicator.stringToProxy('Communicate:tcp -p 10001')
self.contract = Demo_ice._M_demo.PointEventPrx.checkedCast(base)
if not self.contract:
raise RuntimeError('Invalid Proxy')
# 如要调用同步发送方法,方法名去掉Async即可
# 参数加两个括号因为传过去的是个元组
self.contract.OnNewPointEventAsync((self.event)) Client()
4.编写服务器
import Demo_ice
import Ice
import sys class DemoI(Demo_ice._M_demo.PointEvent):
# 不同于Java和C++ Slice出的抽象类,Python的类并不含有异步方法,继承的同步方法可以用于异步调用
def OnNewPointEvent(self, args, current=None):
print "Received:"
print args with Ice.initialize(sys.argv) as communicator:
adapter = communicator.createObjectAdapterWithEndpoints("Communicate:tcp", "tcp -p 10001")
object = DemoI()
adapter.add(object, communicator.stringToIdentity("Communicate"))
adapter.activate()
communicator.waitForShutdown()