我正在尝试通过 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()