• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python远程方法调用实现过程解析

python 搞代码 4年前 (2022-01-07) 34次浏览 已收录 0个评论

这篇文章主要介绍了Python远程方法调用实现过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

RPCHandler 和 RPCProxy 的基本思路是很比较简单的。 如果一个客户端想要调用一个远程函数,比如 foo(1, 2, z=3) ,代理类创建一个包含了函数名和参数的元组 (‘foo’, (1, 2), {‘z’: 3}) 。 这个元组被pickle序列化后通过网络连接发生出去。 这一步在 RPCProxy 的 getattr() 方法返回的 do_rpc() 闭包中完成。

服务器接收后通过pickle反序列化消息,查找函数名看看是否已经注册过,然后执行相应的函数。 执行结果(或异常)被pickle序列化后返回发送给客户端。实例需要依赖 multiprocessing 进行通信。 不过,这种方式可以适用于其他任何消息系统。例如,如果你想在ZeroMQ之上实习RPC, 仅仅只需要将连接对象换成合适的ZeroMQ的socket对象即可。

先实现server端

 import json from multiprocessing.connection import Listener from threading import Thread class RPCHandler: def __init__(self): self._functions = {} def register_function(self, func): self._functions[func.__name__] = func def handle_connection(self, connection): try: while True: func_name, args, kwargs = json.loads(connection.recv()) # Run the RPC and send a response try: r = self._functions[func_name](*args, **kwargs) connection.send(json.dumps(r)) except Exception as e: connection.se<i style="color:transparent">来源gaodai$ma#com搞$$代**码)网</i>nd(json.dumps(e)) except EOFError: pass def rpc_server(handler, address, authkey): sock = Listener(address, authkey=authkey) while True: client = sock.accept() t = Thread(target=handler.handle_connection, args=(client,)) t.daemon = True t.start() # Some remote functions def add(x,y): return x+y if __name__ == '__main__': handler = RPCHandler() handler.register_function(add) # Run the server rpc_server(handler, ('127.0.0.1', 17000), authkey=b'peekaboo')

再实现client端

 import json from multiprocessing.connection import Client class RPCProxy: def __init__(self, connection): self._connection = connection def __getattr__(self, name): def do_rpc(*args, **kwargs): self._connection.send(json.dumps((name, args, kwargs))) result = json.loads(self._connection.recv()) if isinstance(result, Exception): raise result return result return do_rpc if __name__ == '__main__': c = Client(('127.0.0.1', 17000), authkey=b'peekaboo') proxy = RPCProxy(c) res = proxy.add(2, 3) print(res)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持gaodaima搞代码网

以上就是Python远程方法调用实现过程解析的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python远程方法调用实现过程解析
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址