idl的保留關鍵字:'byte','bool','short','int','long','float','double','string' ,均不能用于定義module,class,interface和變量名稱
}
xx結構的from變量名將生成from_
接口定義:
module test{
dictionary<string,string> Properties_t;
sequence<string> IpAddressList_t;
interface ITerminal{
void onGetServerMessage(string text);
}
interface Server{
IpAddressList_t getIpAddresses();
Properties_t getProperties();
void ping(string fromhost);
string login(string user,string passwd,ctx);
};
}
struct:
tce將結構struct映射為class對象 ,初始化成員變量并創建散列函數 marshall/unmarshall
sequence<T>:
tce將數組類型直接映射為[]
例如 :
dictionary<K,V>
tce將字典映射為 {}
python實現Server接口的getIpAddresses()方法:
def getIpAddresses():
return ['192.168.14.101','192.168.12.50']
定義服務器接口實現:
tce為interface生成接口基類: class Server
我們提供一個實現類 :
class ServerImpl(Server):
def __init__(self):
Server.__init__(self)
def getIpAddresses(self,ctx):
return []
在這里我們提供了ServerImpl類,然后編寫實現函數getIpAddresses. 每個接口函數都攜帶ctx參數,ctx攜帶rpc請求的附屬信息,比如: 外帶數據(dict),底部的連接對象 等等 。
服務接口被稱為一個服務類servant ,接下來演示如何將這個servant裝配并提供客戶。
tce.RpcCommunicator.instance().init()
ep = tce.RpcEndPoint(host='127.0.0.1',port=16005) 定義一個通信端點
adapter = tce.RpcCommunicator.instance().createAdapter('first_server',ep) 創建一個通信適配器
servant = ServerImpl() 創建服務接口對象
adapter.addServant(servant) 添加進適配器
tce.RpcCommunicator.instance().waitForShutdown() 進入通信循環
調用服務:
tce.RpcCommunicator.instance().init()
prx = test.ServerProxy.create(127.0.0.1,16005)
ips = prx.getIpAddresses()
多種呼叫模式:
tce將接口函數自動生成 normal,oneway,async三種調用接口方法 ,rpc調用出現異常,底部將拋出異常,所以用戶需要異常捕獲。
1.normal:
原型: fun_name(參數..,timeout=0,extra=None)
調用函數自動添加timeout,extra參數。timeout默認為0,將自動采用tce默認的30s等待調用返回時間;
extra 指此次調用攜帶的附屬數據,extra ={'name':'scott','age':100}
extra數據在服務端接口函數的ctx中獲取: ctx.msg.extra
函數調用時將阻塞客戶線程,直到timeout超時或者服務器數據返回
2. oneway
fun_name_oneway(參數...,extra=None)
只有類型void的接口函數才會生成oneway調用方法.oneway調用不會阻塞用戶線程,通常用于單向傳輸的場景,例如 Server接口的ping()函數
3. async
fun_name_async(參數,async_callback,extra=None)
異步調用模式不會阻塞客戶線程,async_callback指定了rpc調用的返回接收函數
接收函數原型: void fun_name_CallBack(result,proxy)
例如:
def getIpAddressesResult(result,proxy):
print result #result - IpAddressList_t
prx.getIpAddresses_async(getIpAddressesResult)
1. 客戶端定義接收消息的接口 ITerminal,定義接收函數onGetServerMessage()
...
2. 創建到服務器的連接代理
3. 添加服務類實現
3. 請求一次調用
4. 服務器端反向調用ITerminal的onGetServerMessage()