【问题标题】:How to call Python Tornado Websocket Server inside another Python如何在另一个 Python 中调用 Python Tornado Websocket 服务器
【发布时间】:2022-01-01 23:03:06
【问题描述】:

我想在另一个 Python(主)中实现 Python Tornado Websocket 服务器,并在需要时触发发送消息。 main 创建了两个线程。其中一个用于 Python Server,另一个用于触发消息的循环。

当我从初始状态启动服务器时,服务器工作正常,但是因为它无穷无尽的主要文件无法运行。所以我在一个线程内启动服务器,但这次我收到“RuntimeError: There is no current event loop in thread 'Thread-1 (start_server)'”

Main.py

import tornadoserver
import time
from threading import Lock, Thread

class Signal:
    def __init__(self):
        #self.socket = tornadoserver.initiate_server()
        print("start")

    def start_server(self):
        print("start Server")
        self.socket = tornadoserver.initiate_server()

    def brd(self):
        print("start Broad")
        i = 0
        while True:
            time.sleep(3)
            self.socket.send(i)
            i = i + 1

    def job(self):
        # --------Main--------
        threads = []
        for func in [self.start_server, self.brd, ]:
            threads.append(Thread(target=func))
            threads[-1].start()

        for thread in threads:
            thread.join()

Signal().job()

tornadoserver.py

import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.websocket as ws
from tornado.options import define, options
import time

define('port', default=4041, help='port to listen on')
ws_clients = []


class web_socket_handler(ws.WebSocketHandler):

    @classmethod
    def route_urls(cls):
        return [(r'/', cls, {}), ]

    def simple_init(self):
        self.last = time.time()
        self.stop = False

    def open(self):

        self.simple_init()
        if self not in ws_clients:
            ws_clients.append(self)
            print("New client connected")
            self.write_message("You are connected")

    def on_message(self, message):
        if self in ws_clients:
            print("received message {}".format(message))
            self.write_message("You said {}".format(message))
            self.last = time.time()

    def on_close(self):
        if self in ws_clients:
            ws_clients.remove(self)
            print("connection is closed")
            self.loop.stop()

    def check_origin(self, origin):
        return True

    def send_message(self, message):
        self.write_message("You said {}".format(message))


def send(message):
    for c in ws_clients:
        c.write_message(message)


def initiate_server():
    # create a tornado application and provide the urls
    app = tornado.web.Application(web_socket_handler.route_urls())

    # setup the server
    server = tornado.httpserver.HTTPServer(app)
    server.listen(options.port)

    # start io/event loop
    tornado.ioloop.IOLoop.instance().start()

【问题讨论】:

    标签: python python-3.x multithreading tornado


    【解决方案1】:

    使用 Google 我发现了龙卷风问题

    Starting server in separate thread gives... RuntimeError: There is no current event loop in thread 'Thread-4' · Issue #2308 · tornadoweb/tornado

    它表明它必须使用

    asyncio.set_event_loop(asyncio.new_event_loop())
    

    在新线程中运行事件循环

    类似的东西

    import asyncio
    
    # ...
    
    def initiate_server():
    
        asyncio.set_event_loop(asyncio.new_event_loop())  # <---
    
        # create a tornado application and provide the urls
        app = tornado.web.Application(web_socket_handler.route_urls())
    
        # setup the server
        server = tornado.httpserver.HTTPServer(app)
        server.listen(options.port)
    
        # start io/event loop
        tornado.ioloop.IOLoop.instance().start()
    

    【讨论】:

    • 解决了这个问题。之后,我在发送功能中收到了类似的异常。在 send 中添加了以下代码也解决了这个问题。谢谢def send(message): print(ws_clients) try: asyncio.get_event_loop() except RuntimeError as ex: if "There is no current event loop in thread" in str(ex): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) asyncio.get_event_loop() for c in ws_clients: c.write_message(message)
    猜你喜欢
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多