首页 > 解决方案 > 使用 websocket 的龙卷风/异步问题

问题描述

我正在将我的应用程序从 Python 2 转换为 Python 3。简而言之,我的应用程序在 Python(服务器)和 Javascript(客户端)中工作,它们通过 websocket 连接,我使用 tornado 连接。在 Python,我有多个线程。我没有在任何地方使用 Python3 的 asyncio 方法。

但是,在将我的应用程序从 Python 2.7(它在 Python2 中完美运行)转换为 Python 3.7 时,我遇到了 tornado/asyncio 的问题。

首先,我得到了错误:RuntimeError: There is no current event loop in thread 'Thread-26'.

经过一番谷歌搜索后,我发现了一个缓解这种情况的建议:

import tornado.platform.asyncio
import asyncio
asyncio.set_event_loop_policy(tornado.platform.asyncio.AnyThreadEventLoopPolicy())

这似乎解决了该错误。但是,现在我收到以下警告+错误:

2019-08-24 13:27:25,455 asyncio      DEBUG    Using selector: SelectSelector
2019-08-24 13:28:25,455 asyncio      ERROR    Task was destroyed but it is pending!
task: <Task pending coro=<WebSocketProtocol13.write_message.<locals>.wrapper() running at C:\Users\DLA\PycharmProjects\myPmese\Python3\lib\site-packages\tornado\websocket.py:1102>>

关于发生了什么的任何线索?不幸的是,我找不到我的 Python 代码的确切部分导致了这种情况。

非常感谢!任何帮助,将不胜感激 :)

您可以在下面使用 tornado 找到我的 Python websocket 的架构:

import tornado.platform.asyncio
import asyncio
asyncio.set_event_loop_policy(tornado.platform.asyncio.AnyThreadEventLoopPolicy())
application = tornado.web.Application([(r'/myPmese/websocket', WSocketHandler)])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8295)
tornado.ioloop.IOLoop.instance().start()

class WSocketHandler(tornado.websocket.WebSocketHandler):

    def initialize(self):
        print('initialize') # here I initialise handlers

    def open(self):
        start_server_code()  # triggers the code from the server.

    def __call__(self, *args):
        clientCommand = self.getClientCommand()
        self.resetClientCommand()
        self.send(clientCommand , *args)

    def send(self, var_func, *args):
        try:
            self.write_message(json.dumps(self.getClientCommand()))
        except Exception as e:
            print(traceback.format_exc())

    def on_message(self, message):
        if message != '':
            try:
                eval(self.executeCommand(message))
            except Exception as e:
                print(traceback.format_exc())
                self.send('createErrorMessage', str(e))

    def on_close(self):
        tornado.ioloop.IOLoop.instance().stop()

标签: pythonpython-3.xwebsockettornadopython-asyncio

解决方案


推荐阅读