python tornado websocket错误:RuntimeError:线程中没有当前的事件循环' Thread-1'

时间:2018-05-04 09:13:59

标签: python tornado


我有以下代码,它在Tornado< 5上运行良好但如果我通过Tornado> = 5运行它会失败,

import tornado.httpserver
import tornado.ioloop
import threading
import tornado.web,tornado.websocket

class thr(threading.Thread):
    def __init__(self,handler):
        self.handler=handler
        threading.Thread.__init__(self)
    def run(self):
        self.handler.write_message("test")
class ClientWebSocketConnectionHandler(tornado.websocket.WebSocketHandler):
    def open(self):
            print ("opened")
    def on_message(self, message):
            thr(self).start()    

class MainApplication(tornado.web.Application):
    def __init__(self):
        handlers = [(r'/User', ClientWebSocketConnectionHandler),]
        tornado.web.Application.__init__(self, handlers,)

TheShieldsWebSocket = MainApplication()
server = tornado.httpserver.HTTPServer(TheShieldsWebSocket)
server.listen(8085,'0.0.0.0')
tornado.ioloop.IOLoop.instance().start()



错误说:RuntimeError: There is no current event loop in thread 'Thread-1'

什么错了?看起来它与线程有关。

1 个答案:

答案 0 :(得分:0)

假设你想写一个api,这个api可能需要在渲染之前等待客户端!这里有seriv方式来实现这一点!因为你使用thread,这很好,但不推荐。所以我们在龙卷风中调用并发,你可以看到详细信息here

在这里你的代码可以修改如下:

import tornado.httpserver
import tornado.ioloop
import tornado.web,tornado.websocket


class ClientWebSocketConnectionHandler(tornado.websocket.WebSocketHandler):
    def open(self):
            print ("opened")
    def on_message(self, message):
            self.write_message('test')    

class MainApplication(tornado.web.Application):
    def __init__(self):
        handlers = [(r'/User', ClientWebSocketConnectionHandler),]
        tornado.web.Application.__init__(self, handlers,)

TheShieldsWebSocket = MainApplication()
server = tornado.httpserver.HTTPServer(TheShieldsWebSocket)
server.listen(8085,'0.0.0.0')
tornado.ioloop.IOLoop.instance().start()

通常,您会收到403错误,在这种情况下,您可以将函数名称添加为check_origin

    # rest of above code
    def check_origin(self, param):
            return True

    def open(self):
            print ("opened")
    def on_message(self, message):
            self.write_message('test') 

然后如果你想要服务器可以处理多个连接,你可以使用`并发方式来做到这一点:

    @gen.coroutine
    def on_message(self, message):
            http_client = AsyncHTTPClient()
            response = yield http_client.fetch("http://example.com")
            do_something_with_response(response)
            self.write_message('test')