我正试图建立一个通过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()
我偶然发现了类似的问题。这是我的解决办法。希望这对外面的人有帮助
要向WebSocket发送消息,只需使用以下命令:
wsSend更新
我偶尔会遇到wsSend的例外。为了解决这个问题,我将代码修改为:
你可以打电话给
在指定的截止时间超时时调用回调(一次,但可以重新安排),或使用
tornado.ioloop.PeriodicCallback
如果你有更定期的任务。见:http://www.tornadoweb.org/en/stable/ioloop.html#tornado.ioloop.IOLoop.add_timeout
更新:一些示例
它在5秒后调用
test()
。更新2:
另一种方法是使用pub sub模块。
这意味着您有自己的连接subscribe,而不是为每个连接设置超时,您只需在上述时间段后将一个超时设置为publish。
可能实现得最多的是redis。也有一些模块专门针对龙卷风:例如toredis或brükva。
当然,这对于一个简单的页面来说可能不是必需的,但是它的伸缩性非常好,而且一旦您设置好它,就可以很好地进行维护/扩展。
相关问题 更多 >
编程相关推荐