我有一个像下面这样的远程服务器,它已经有一个初始化的类,并且我将协议配置设置为允许公共属性 True。
import rpyc
class SharedClass(object):
def __init__(self,string):
print string
def action(self):
print 'i am doing something'
s=SharedClass('hi')
class MyService(rpyc.Service):
def on_connect(self):
pass
def on_disconnect(self):
pass
def exposed_get_shared(self):
return s
if __name__=='__main__:
from rpyc.utils.server import ThreadedServer
t=ThreadedServer(MyService,port=18861,protocol_config={"allow_public_attrs":True})
t.start()
在客户端,如果我尝试直接连接它正在工作,而当我尝试在函数内部建立连接并返回对象时,我收到错误
**客户**
**直接连接**
>>>Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
>>>Type "help", "copyright", "credits" or "license" for more information.
>>>conn=rpyc.connect('localhost',18861)
>>>share=getattr(conn.root,'get_shared')
>>>share
<bound method MyService.exposed_get_shared of <__main__.MyService
object at 0x011BA698>>
>>>share=getattr(conn.root,'get_shared')()
>>>share
<__main__.SharedClass object at 0x00B6ED30>
>>>share.action()
i am doing something
如果我尝试在函数中执行此操作,则会出现错误;(
>>>def returnObject(objName, host, port):
... conn = rpyc.connect(host, port)
... print conn
... attr = getattr(conn.root, 'get_' + objName)()
... print attr
... return attr
>>>share=returnObject('shared','localhost',18861)
<rpyc.core.protocol.Connection 'conn2' object at 0x0108AAD0>
<__main__.SharedClass object at 0x00B6ED30>
>>>share
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\rpyc\core\netref.py", line 168,
in __repr__
return syncreq(self, consts.HANDLE_REPR)
File "C:\Python27\lib\site-packages\rpyc\core\netref.py", line 69,
in syncreq
return conn().sync_request(handler, oid, *args)
AttributeError: 'NoneType' object has no attribute 'sync_request'
我的目的是在服务器中初始化一个对象并让许多客户端访问它。初始化的类是线程安全的,因此多个客户端可以使用它。
我意识到我在这样做时遗漏了一些东西。
--
阿迪提亚