Twisted中 pb 透明代理简介

来源:互联网 发布:政府的层级结构优化 编辑:程序博客网 时间:2024/06/05 09:36

透明代理(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)
Parametersrootfactory providing the root Referenceable used by the broker. (type: object providing or adaptable to IPBRoot. ) unsafeTracebacksif set, tracebacks for exceptions will be sent over the wire. (type: bool ) securitysecurity 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_namethe name of the remote method to invoke (type: string )   (远程方法要调用的名字) argsarguments to serialize for the remote function  元组参数 kwkeyword arguments to serialize for the remote function. 字典参数Returnsa Deferred which will be fired when the result of this remote call is received. (type: twisted.internet.defer.Deferred )
0 0