zoukankan      html  css  js  c++  java
  • python实现远程方法调用

    先实现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)
  • 相关阅读:
    关于dllimport的使用
    公众平台返回原始数据为: 错误代码-40164
    CentOS7.4 系统下 Tomcat 启动慢解决方法
    PyCharm实现高效远程调试代码
    代码比较工具推荐
    CentOS7 下源码安装 python3
    linux定时任务调度定系统——opencron
    使用 ISO镜像配置 本地yum 源(RHEL, CentOS, Fedora等适用)
    Error: rpmdb open failed
    部署Redis(脚本安装)
  • 原文地址:https://www.cnblogs.com/wangbin2188/p/13177065.html
Copyright © 2011-2022 走看看