如何在python中的websocket循环外运行函数(tornado)

2024-09-28 17:24:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图建立一个通过websockets的公共Twitter流的小例子。这是我的websocket.py,正在工作。

我想知道的是:如何从类WSHandler的“外部”与websocket进行交互(即,当接收到来自websocket.js的消息时不仅要应答)?假设我想在同一个脚本中运行另一个函数,该脚本将显示“hello!”每隔5秒发送到websocket(浏览器),而不需要客户端进行任何交互。我怎么能那样做?

所以这是一个基本的初学者问题,我想,关于如何处理下面的课程。任何方向的指针都将非常感谢!

import os.path
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web

# websocket
class FaviconHandler(tornado.web.RequestHandler):
    def get(self):
        self.redirect('/static/favicon.ico')

class WebHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("websockets.html")

class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        print 'new connection'
        self.write_message("Hi, client: connection is made ...")

    def on_message(self, message):
        print 'message received: \"%s\"' % message
        self.write_message("Echo: \"" + message + "\"")
        if (message == "green"):
            self.write_message("green!")

    def on_close(self):
        print 'connection closed'



handlers = [
    (r"/favicon.ico", FaviconHandler),
    (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': 'static'}),
    (r'/', WebHandler),
    (r'/ws', WSHandler),
]

settings = dict(
    template_path=os.path.join(os.path.dirname(__file__), "static"),
)

application = tornado.web.Application(handlers, **settings)

if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

Tags: pathimportselfwebmessageosdefstatic
3条回答

我偶然发现了类似的问题。这是我的解决办法。希望这对外面的人有帮助

wss = []
class wsHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        print 'Online'
        if self not in wss:
            wss.append(self)

    def on_close(self):
        print 'Offline'
        if self in wss:
            wss.remove(self)

def wsSend(message):
    for ws in wss:
        ws.write_message(message)

要向WebSocket发送消息,只需使用以下命令:

wsSend(message)

wsSend更新

我偶尔会遇到wsSend的例外。为了解决这个问题,我将代码修改为:

def wsSend(message):
    for ws in wss:
        if not ws.ws_connection.stream.socket:
            print "Web socket does not exist anymore!!!"
            wss.remove(ws)
        else:
            ws.write_message(message)

你可以打电话给

IOLoop.add_timeout(deadline, callback)

在指定的截止时间超时时调用回调(一次,但可以重新安排),或使用

tornado.ioloop.PeriodicCallback如果你有更定期的任务。

见:http://www.tornadoweb.org/en/stable/ioloop.html#tornado.ioloop.IOLoop.add_timeout

更新:一些示例

import datetime

def test():
    print "scheduled event fired"
...

if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    main_loop = tornado.ioloop.IOLoop.instance()
    # Schedule event (5 seconds from now)
    main_loop.add_timeout(datetime.timedelta(seconds=5), test)
    # Start main loop
    main_loop.start()

它在5秒后调用test()

更新2:

import os.path
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web

# websocket
class FaviconHandler(tornado.web.RequestHandler):
    def get(self):
        self.redirect('/static/favicon.ico')

class WebHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("websockets.html")

class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        print 'new connection'
        self.write_message("Hi, client: connection is made ...")
        tornado.ioloop.IOLoop.instance().add_timeout(datetime.timedelta(seconds=5), self.test)

    def on_message(self, message):
        print 'message received: \"%s\"' % message
        self.write_message("Echo: \"" + message + "\"")
        if (message == "green"):
            self.write_message("green!")

    def on_close(self):
        print 'connection closed'

    def test(self):
        self.write_message("scheduled!")

handlers = [
    (r"/favicon.ico", FaviconHandler),
    (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': 'static'}),
    (r'/', WebHandler),
    (r'/ws', WSHandler),
]

settings = dict(
    template_path=os.path.join(os.path.dirname(__file__), "static"),
)

application = tornado.web.Application(handlers, **settings)

import datetime

if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

另一种方法是使用pub sub模块。

这意味着您有自己的连接subscribe,而不是为每个连接设置超时,您只需在上述时间段后将一个超时设置为publish。

可能实现得最多的是redis。也有一些模块专门针对龙卷风:例如toredisbrükva

当然,这对于一个简单的页面来说可能不是必需的,但是它的伸缩性非常好,而且一旦您设置好它,就可以很好地进行维护/扩展。

相关问题 更多 >