31

我正在尝试通过 websockets 设置一个公共 Twitter 流的小示例。这是我的 websocket.py,它正在工作。

我想知道的是:如何从类 WSHandler 的“外部”与 websocket 交互(即,不仅在接收来自 websocket.js 的消息时回答)?假设我想在同一个脚本中运行一些其他功能,这些功能会发布“你好!” 每五秒钟将其发送到 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()
4

3 回答 3

21

你可以打电话给

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()

test()它会在 5 秒后调用。

更新 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()
于 2012-09-18T14:48:42.040 回答
16

我偶然发现了类似的问题。这是我的解决方案。希望这对那里的人有帮助

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)

ws发送更新

我偶尔会遇到 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)
于 2013-03-18T22:48:27.440 回答
2

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

这意味着您有您的连接订阅它,而不是为每个连接设置超时,您只需设置一个超时以在所述时间段后发布。

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

当然,对于一个简单的页面来说,这可能不是必需的,但是可以很好地扩展,并且一旦设置好它就可以很好地维护/扩展。

于 2014-07-01T08:58:04.643 回答