如何向所有客户端发送数据?

How to send data to all clients?

我有简单的服务器:

# -*- coding: utf-8 -*-

import os
import logging
import tornado.httpserver
import tornado.ioloop
import tornado.options


class WSHandler(tornado.websocket.WebSocketHandler):

    def check_origin(self, origin):
        return True

    def open(self):
        print 'connection opened'

    def on_message(self, message):
        self.write_message("Echo: " + message)
        print 'received:', message

    def on_close(self):
        print 'connection closed'


class MainHandler(tornado.web.RequestHandler):

    def get(self):
        self.write('OK')


url_patterns = [
    (r'/ws', WSHandler),
    (r'/update', MainHandler),
]

application = tornado.web.Application(
    url_patterns,
    debug=False
)

if __name__ == "__main__":
    application.listen(9991)
    tornado.ioloop.IOLoop.instance().start()

当我从浏览器调用“/update”时,我想通过 websocket 向所有连接的客户端发送一些数据。怎么做?

clients = []

class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        clients.append(self)
        print 'connection opened'

    def on_close(self):
        clients.remove(self)
        print 'connection closed'


class MainHandler(tornado.web.RequestHandler):

    def get(self):
        for client in clients:
             client.write_message('OK')
        self.write('OK')