使用Autobahn的远程调用模式
生活随笔
收集整理的這篇文章主要介紹了
使用Autobahn的远程调用模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Autobahn提供了遠程調用模式(RPC = Remote Procedure Calls),服務器寫好供調用的函數并注冊一個uri,客戶端調用函數時對應的代碼就會在服務器上跑一遍并返回結果給客戶端。
?常用相關函數:
服務器端:
注冊一個服務object用于rpc:
registerForRpc(obj, baseUri='')obj指定執行代碼時的self,baseuri為客戶端call時的前綴。這個函數將會把obj所屬類中所有帶@exportRpc的方法提供給客戶端調用。
實際執行的代碼相當于obj.(realUri-baseUri)
注冊一個obj和其中的一個方法:
registerMethodForRpc(uri, obj, proc)注冊一個全局函數:
registerProcedureForRpc(uri, proc)?
js客戶端:
遠程調用函數:
Session.call ( method, ... )method是一個uri,用它減去服務器中注冊的baseUri即為調用的方法名,后跟變長參數列表。
如需注冊回調函數,可以使用then()方法分別給執行成功和失敗注冊。類似如下代碼:
sess.call("http://example.com#test", 1, 2, 3).then(function(res){}, function(error) {})?
完整程序:
服務器端:
from twisted.internet import reactor from autobahn.wamp import exportRpc, \WampServerFactory, \WampServerProtocol from autobahn.websocket import listenWSclass MyProtocol(WampServerProtocol):def onSessionOpen(self): # 因為輸出的函數都在本類里,故第一個參數為self # 否則需要實例化一個含輸出函數的類做為參數self.registerForRpc(self, "http://example.com/rpc#") # @exportRpc說明此函數會被輸出@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是一個我自己寫的函數用于顯示提示消息 $.setHint("connecting");ab.connect("ws://" + location.hostname + ":9000", function (session) { // 連接成功后執行的函數 $.setHint();sess = session; // 遠程調用,可以看到這里的uri比服務器中注冊的http://example.com/rpc多了login,故調用的是login函數,后跟變長參數列表 // .then指定回調函數sess.call("http://example.com/rpc#login", username).then(function (res) { // 執行成功后的函數,res為返回值},function (error) { // 執行失敗的函數,可以通過error.desc查看具體原因$.setHint("failed");});},function (code, reason) { // 連接斷開后執行的函數sess = null;$.setHint("failed");});$("#new").click(function() { // 遠程調用new函數,后跟三個參數sess.call("http://example.com/rpc#new", username, username, 5).then(function (res) { // 執行成功后location = "game.html"},function (error) { // 執行失敗后$.setHint("newmfailed");});}); });
?
總結
以上是生活随笔為你收集整理的使用Autobahn的远程调用模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Wordpress建站-wp建站网站优化
- 下一篇: [转载]***编年史 之 上帝派来的**