需要安装rpyc模块
pip install rpyc
服务端示例server.py:
from rpyc import Service
from rpyc.utils.server import ThreadedServer
class A():
def __init__(a):
self.a = a
a = A(233)
class TestService(Service):
# 需要些exposed_开头,表示公开暴露的方法
def exposed_getA(self):
return a
print('远端服务端启动')
# protocol_config配置表示开放远端对象的属性访问
server = ThreadedServer(TestService, auto_register=False, hostname = 'localhost', port=9999, protocol_config={"allow_all_attrs":True,
"allow_setattr": True,
"allow_delattr": True,})
server.start()
本地代码local.py:
import rpyc
conn = rpyc.connect(host="localhost", port=9999)
aaa = conn.root.getA()
print(aaa) # 得到的是远端的A()对象的内存地址
print(aaa.a) # 输出结果为233
conn.close()