使用Tornado websocket定期进行乒乓球比赛

时间:2017-11-28 14:01:41

标签: python websocket tornado

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

我需要做的就是不断ping与客户有关的客户。

1 个答案:

答案 0 :(得分:1)

websocket_ping_interval是一个应用程序设置,因此您将其传递给Application构造函数:

app = tornado.web.Application(handlers, websocket_ping_interval=10)