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