欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2021-05-14 10:39:34|栏目: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.send(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)

上一篇:在Mac OS系统上安装Python的Pillow库的教程

栏    目:Python代码

下一篇:将python运行结果保存至本地文件中的示例讲解

本文标题:Python远程方法调用实现过程解析

本文地址:http://www.codeinn.net/misctech/121334.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有