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 rootfactory 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. 字典参数
Returns a Deferred which will be fired when the result of this remote call is received. (type: twisted.internet.defer.Deferred )
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值