栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/17851.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号