带有Autobahn、ApplicationRunner和ApplicationSession的多线程 [英] Multiple thread with Autobahn, ApplicationRunner and ApplicationSession

查看:23
本文介绍了带有Autobahn、ApplicationRunner和ApplicationSession的多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python-running-autobahnpython-asyncio-websocket-server-in-a-separate-subproce

can-an-asyncio-event-loop-run-in-the-background-without-suspending-the-python-in

我正在尝试使用上面的这两个链接解决我的问题,但我没有解决。

我有以下错误:运行错误:线程‘Thread-1’中没有当前事件循环。

这里是代码示例(Python3):

from autobahn.asyncio.wamp import ApplicationSession
from autobahn.asyncio.wamp import ApplicationRunner
from asyncio import coroutine
import time
import threading


class PoloniexWebsocket(ApplicationSession):

    def onConnect(self):
        self.join(self.config.realm)

    @coroutine
    def onJoin(self, details):

        def on_ticker(*args):
            print(args)

        try:
            yield from self.subscribe(on_ticker, 'ticker')

        except Exception as e:
            print("Could not subscribe to topic:", e)


def poloniex_worker():
    runner = ApplicationRunner("wss://api.poloniex.com:443", "realm1")
    runner.run(PoloniexWebsocket)


def other_worker():
    while True:
        print('Thank you')
        time.sleep(2)


if __name__ == "__main__":
    polo_worker = threading.Thread(None, poloniex_worker, None, (), {})
    thank_worker = threading.Thread(None, other_worker, None, (), {})

    polo_worker.start()
    thank_worker.start()

    polo_worker.join()
    thank_worker.join()

所以,我的最终目标是在开始时启动两个线程。只有一个需要使用ApplicationSession和ApplicationRunner。谢谢。

推荐答案

单独的线程必须有自己的事件循环。因此,如果Poloniex_Worker需要监听WebSocket,它需要自己的事件循环:

def poloniex_worker():
    asyncio.set_event_loop(asyncio.new_event_loop())
    runner = ApplicationRunner("wss://api.poloniex.com:443", "realm1")
    runner.run(PoloniexWebsocket)
但是,如果您是在Unix计算机上,如果您尝试这样做,您将面临另一个错误。Autobahn asyncio使用Unix信号,但这些Unix信号只在主线程中工作。如果您不打算使用Unix信号,只需将其关闭即可。为此,您必须转到定义了ApplicationRunner的文件。这就是我机器上的python3.5>Site-Packages>Autobahn>asyncio中的wamp.py。您可以注释掉代码的信号处理部分,如下所示:

# try:
#     loop.add_signal_handler(signal.SIGTERM, loop.stop)
# except NotImplementedError:
#     # signals are not available on Windows
#     pass

所有这些都是大量的工作。如果您完全不需要在与主线程不同的线程中运行ApplicationSession,则最好只在主线程中运行ApplicationSession。

这篇关于带有Autobahn、ApplicationRunner和ApplicationSession的多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆