使用Autobahn的远程调用模式
Autobahn提供了遠(yuǎn)程調(diào)用模式(RPC = Remote Procedure Calls),服務(wù)器寫(xiě)好供調(diào)用的函數(shù)并注冊(cè)一個(gè)uri,客戶端調(diào)用函數(shù)時(shí)對(duì)應(yīng)的代碼就會(huì)在服務(wù)器上跑一遍并返回結(jié)果給客戶端。
?常用相關(guān)函數(shù):
服務(wù)器端:
注冊(cè)一個(gè)服務(wù)object用于rpc:
registerForRpc(obj, baseUri='')obj指定執(zhí)行代碼時(shí)的self,baseuri為客戶端call時(shí)的前綴。這個(gè)函數(shù)將會(huì)把obj所屬類(lèi)中所有帶@exportRpc的方法提供給客戶端調(diào)用。
實(shí)際執(zhí)行的代碼相當(dāng)于obj.(realUri-baseUri)
注冊(cè)一個(gè)obj和其中的一個(gè)方法:
registerMethodForRpc(uri, obj, proc)注冊(cè)一個(gè)全局函數(shù):
registerProcedureForRpc(uri, proc)?
js客戶端:
遠(yuǎn)程調(diào)用函數(shù):
Session.call ( method, ... )method是一個(gè)uri,用它減去服務(wù)器中注冊(cè)的baseUri即為調(diào)用的方法名,后跟變長(zhǎng)參數(shù)列表。
如需注冊(cè)回調(diào)函數(shù),可以使用then()方法分別給執(zhí)行成功和失敗注冊(cè)。類(lèi)似如下代碼:
sess.call("http://example.com#test", 1, 2, 3).then(function(res){}, function(error) {})?
完整程序:
服務(wù)器端:
from twisted.internet import reactor from autobahn.wamp import exportRpc, \WampServerFactory, \WampServerProtocol from autobahn.websocket import listenWSclass MyProtocol(WampServerProtocol):def onSessionOpen(self): # 因?yàn)檩敵龅暮瘮?shù)都在本類(lèi)里,故第一個(gè)參數(shù)為self # 否則需要實(shí)例化一個(gè)含輸出函數(shù)的類(lèi)做為參數(shù)self.registerForRpc(self, "http://example.com/rpc#") # @exportRpc說(shuō)明此函數(shù)會(huì)被輸出@exportRpcdef login(self, username):print "login"@exportRpcdef new(self, username, roomname, size):print "new"@exportRpcdef join(self, username, roomname):print "join"@exportRpcdef exit(self, username, roomname):print "exit"if __name__ == '__main__':factory = WampServerFactory("ws://localhost:9000")factory.protocol = MyProtocollistenWS(factory)reactor.run()js客戶端:
$(document).ready(function() {var username = $.cookie("username");var sess;// setHint是一個(gè)我自己寫(xiě)的函數(shù)用于顯示提示消息 $.setHint("connecting");ab.connect("ws://" + location.hostname + ":9000", function (session) { // 連接成功后執(zhí)行的函數(shù) $.setHint();sess = session; // 遠(yuǎn)程調(diào)用,可以看到這里的uri比服務(wù)器中注冊(cè)的http://example.com/rpc多了login,故調(diào)用的是login函數(shù),后跟變長(zhǎng)參數(shù)列表 // .then指定回調(diào)函數(shù)sess.call("http://example.com/rpc#login", username).then(function (res) { // 執(zhí)行成功后的函數(shù),res為返回值},function (error) { // 執(zhí)行失敗的函數(shù),可以通過(guò)error.desc查看具體原因$.setHint("failed");});},function (code, reason) { // 連接斷開(kāi)后執(zhí)行的函數(shù)sess = null;$.setHint("failed");});$("#new").click(function() { // 遠(yuǎn)程調(diào)用new函數(shù),后跟三個(gè)參數(shù)sess.call("http://example.com/rpc#new", username, username, 5).then(function (res) { // 執(zhí)行成功后location = "game.html"},function (error) { // 執(zhí)行失敗后$.setHint("newmfailed");});}); });
?
總結(jié)
以上是生活随笔為你收集整理的使用Autobahn的远程调用模式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Wordpress建站-wp建站网站优化
- 下一篇: [转载]***编年史 之 上帝派来的**