我需要创建一个独立的类,它使用wamp和autobahn提供在自己的Python进程中运行的RPC服务器。
按照此处的一些指南,我设法在这些类中创建此服务器保存到文件 rpcwampserver.py :
from twisted.internet.defer import inlineCallbacks
from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner
import multiprocessing
from twisted.internet import reactor
class Manager(ApplicationSession):
@inlineCallbacks
def onJoin(self, details):
print("session ready")
def test():
return u'hello!'
try:
yield self.register(test, u'rpc.test')
print("procedure registered")
except Exception as e:
print("could not register procedure: {0}".format(e))
class RPCWampServer:
def __init__(self):
self._url = u'ws://localhost:8080/ws'
self.real = u'realm'
self.runner = ApplicationRunner(url=self._url, realm=self.realm,
#debug=True, debug_wamp=True, debug_app=True
)
def start(self):
self.runner.run(Manager, start_reactor=False)
class RPC_Wamp_Server:
def __init__(self):
server = RPCWampServer()
server.start()
multi = multiprocessing.Process(target=reactor.run,args=())
multi.start()
如果将RPC_Wamp_Server直接导入到靠近rpcwampserver.py的文件中,则代码可以正常工作:
from rpcwampserver import RPC_Wamp_Server
c=RPC_Wamp_Server()
如果我在位于不同路径的包中使用此类,则反应堆不起作用:
from mymodules.wamp.rpcwampserver import RPC_Wamp_Server
c=RPC_Wamp_Server()
找到了类 RPC_Wamp_Server ,但似乎跳过了Manager的初始化。
启用调试(在代码中注释)它出现:
Starting factory [...]
过了一会儿
Stopped factory [...]
编辑: 使用127.0.0.1而不是localhost解决了问题