Twisted中 pb 透明代理簡介

透明代理(PB, Perspective Broker)是用於遠程方法調用和對象交換協議,該協議是異步和對稱的。使用PB, 客戶端可以直接調用服務器的函數並得到函數的返回結果。
    Twisted針對Server和Client分別提供了pb.PBServerFactory和pb.PBClientFactory供用戶使用, 其中Factory中的root對象必須繼承自pb.Referenceable(pb.root就繼承自pb.Referenceable)。 Sevrer中提供的方法必須以remote_開頭, Client使用該方法時不用指定remote。 例如下面的例子中服務器端提供了remote_echo方法,客戶端使用callRemote("echo", "hi")即可調用該方法。

服務器端:
from twisted.spread import pb
from twisted.internet import reactor

class Echoer(pb.Root):
    def remote_echo(self, st):  //Server中提供的方法必須以remote_開頭
        print 'hi'
        return st

    def remote_test(self):
        return self

if __name__ == '__main__':
    reactor.listenTCP(8003, pb.PBServerFactory(Echoer()))   //Echoer繼承於pb.Root
    reactor.run()

 

pb.PBServerFactory的構造函數如下:
def __init__(self, root, unsafeTracebacks=False, security=globalSecurity): (source)
Parameters root factory providing the root Referenceable used by the broker. (type: object providing or adaptable to IPBRoot. )
  unsafeTracebacks if set, tracebacks for exceptions will be sent over the wire. (type: bool )
  security security options used by the broker, default to globalSecurity. (type: twisted.spread.jelly.SecurityOptions )

 

 

 

 

客戶端:
from twisted.spread import pb
from twisted.internet import reactor
from twisted.python import util

factory = pb.PBClientFactory()
reactor.connectTCP('127.0.0.1', 8003, factory)
d = factory.getRootObject()
d.addCallback(lambda object: object.callRemote("echo", "hi"))  //客戶端使用callRemote("echo", "hi")即可調用服務段的remote_echo()方法,並將"hi"作爲參數傳入。
d.addCallback(lambda result: result)
d.addErrback(lambda reason: 'error: ' + str(reason.value))
d.addCallback(util.println)
d.addCallback(lambda _: reactor.stop())
reactor.run()

    遠程方法調用除了可以返回和傳遞字符串、詞典、列表等簡單對象外,還可以傳遞pb.Referenceable對象。象上面的例子中,可以先調用callRemote("test")來獲得一個新的pb.Referenceable對象,然後在對該對象使用callRemote方法。

 

 

def callRemote(self, _name, *args, **kw): (source)
Asynchronously invoke a remote method.  (異步調用遠程方法)
Parameters _name the name of the remote method to invoke (type: string )   (遠程方法要調用的名字)
  args arguments to serialize for the remote function  元組參數
  kw keyword arguments to serialize for the remote function. 字典參數
Returns a Deferred which will be fired when the result of this remote call is received. (type: twisted.internet.defer.Deferred )
發佈了0 篇原創文章 · 獲贊 0 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章