Pra*_*ati 2 python tornado websocket
我是Python中的Tornado服务器的新手,并尝试定期与连接的客户端进行乒乓球运动。我websocket_ping_interval在龙卷风文档中看到了一些叫做的东西,但找不到任何关于如何/何时使用它的示例。
我使用了以下命令ioloop.PeriodicCallback,但似乎没有执行任何 ping 操作。
import tornado.web
from tornado import ioloop
from terminado import TermSocket, SingleTermManager
from tornado import websocket
# BaseWebSocketHandler removed, because we need to track all opened
# sockets in the class. You could change this later.
class MeterInfo(websocket.WebSocketHandler):
"""Establish an websocket connection and send meter readings."""
opened_sockets = []
previous_meter_reading = 0
def open(self):
self.write_message('Connection Established.')
MeterInfo.opened_sockets.append(self)
def on_close(self):
"""Close the connection."""
self.write_message('bye')
MeterInfo.opened_sockets.remove(self)
@classmethod
def try_send_new_reading(cls):
"""Send new reading to all connected clients"""
new_reading = "text"
if new_reading == cls.previous_meter_reading:
return
cls.previous_meter_reading = new_reading
for socket in cls.opened_sockets:
socket.write_message({'A': new_reading})
if __name__ == '__main__':
term_manager = SingleTermManager(shell_command=['bash'])
handlers = [
(r"/websocket", TermSocket, {'term_manager': term_manager}),
(r"/()", tornado.web.StaticFileHandler, {'path': 'index.html'}),
(r"/(.*)", tornado.web.StaticFileHandler, {'path': '.'}),
]
app = tornado.web.Application(handlers)
app.listen(8010)
METER_CHECK_INTERVAL = 100 # ms
ioloop.PeriodicCallback(MeterInfo.try_send_new_reading,METER_CHECK_INTERVAL).start()
ioloop.IOLoop.instance().start()
Run Code Online (Sandbox Code Playgroud)
我所需要做的就是不断 ping 与某项连接的客户端。
websocket_ping_interval是一个应用程序设置,因此您将其传递给Application构造函数:
app = tornado.web.Application(handlers, websocket_ping_interval=10)
Run Code Online (Sandbox Code Playgroud)