python远程教学_Python远程方法调用实现过程解析

1b886e01fb6cf6771d2069176464ece5.png

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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持云海天教程。

原文链接:https://www.cnblogs.com/wangbin2188/p/13177065.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值