我试图实现一个使用高速公路| python 和asyncio
的websocket/wamp客户端,虽然它有点工作,但也有一些零件不知道 。如何使用autobahn asyncio实现交互式websocket客户端?
我真正想要做的是在qt5/QML中实现WAMP,但这个 看起来像是一个更容易的路径。
这个简化的客户端大部分都是从网上复制过来的。它在onJoin
发生时读取 时间服务。
我想要做的就是触发这个从外部来源读取。
我采取的复杂方法是在 线程中运行asyncio
事件循环,然后通过套接字发送命令来触发读取。 I 到目前为止还无法确定在哪里放置例程/协程,以便可以从读者例行程序中找到它。
我怀疑有一个更简单的方法去做这件事,但我还没有发现它 呢。欢迎提出建议。
#!/usr/bin/python3
try:
import asyncio
except ImportError:
## Trollius >= 0.3 was renamed
import trollius as asyncio
from autobahn.asyncio import wamp, websocket
import threading
import time
from socket import socketpair
rsock, wsock = socketpair()
def reader() :
data = rsock.recv(100)
print("Received:", data.decode())
class MyFrontendComponent(wamp.ApplicationSession):
def onConnect(self):
self.join(u"realm1")
@asyncio.coroutine
def onJoin(self, details):
print('joined')
## call a remote procedure
##
try:
now = yield from self.call(u'com.timeservice.now')
except Exception as e:
print("Error: {}".format(e))
else:
print("Current time from time service: {}".format(now))
def onLeave(self, details):
self.disconnect()
def onDisconnect(self):
asyncio.get_event_loop().stop()
def start_aloop() :
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
transport_factory = websocket.WampWebSocketClientFactory(session_factory,
debug = False,
debug_wamp = False)
coro = loop.create_connection(transport_factory, '127.0.0.1', 8080)
loop.add_reader(rsock,reader)
loop.run_until_complete(coro)
loop.run_forever()
loop.close()
if __name__ == '__main__':
session_factory = wamp.ApplicationSessionFactory()
session_factory.session = MyFrontendComponent
## 4) now enter the asyncio event loop
print('starting thread')
thread = threading.Thread(target=start_aloop)
thread.start()
time.sleep(5)
print("IN MAIN")
# emulate an outside call
wsock.send(b'a byte string')
因此,您希望能够通过某种外部方式触发客户端对timeservice进行RPC调用? – dano 2014-11-03 02:26:17