python - Tornado 发送有关事件的消息

标签 python websocket tornado

我正在用 Python 创建一个程序,以未知的时间间隔读取数据流。该程序还通过 websocket 发送此数据。 该程序是服务器,它将接收到的数据发送给客户端。

这是现在服务器的代码:

class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def initialize(self):
        print 'Websocket opened'

    def open(self):
        print 'New connection'
        self.write_message('Test from server')

    def on_close(self):
        print 'Connection closed'

    def test(self):
        self.write_message("scheduled!")

def make_app():
    return tornado.web.Application([
    (r'/ws', WebSocketHandler),
    ])

if __name__ == '__main__':
    application = make_app()

    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

但我希望能够在此循环中使用write_message:

def read_function():
    while True:
        time.sleep(10) # a while loop to simulate the reading
        print 'read serial'
        str = 'string to send'
        # send message here to the clients

我该怎么做?

编辑:两个线程使用连接都会有问题吗?看起来它适用于 1 个连接。

def read_function():
    while True:
        time.sleep(5) # a while loop to simulate the reading
        print 'read serial'
        str = 'string to send'
        [client.write_message(str) for client in connections]

if __name__ == '__main__':
    thread = Thread(target = read_function)
    application = make_app()
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    thread.start()
    tornado.ioloop.IOLoop.instance().start()
    thread.join()

最佳答案

在 WebsocketHandler 外部使用 connections = set(),并在使用 connections.add(self) 打开连接时添加每个客户端。不要忘记在关闭时使用 connections.remove(self) 删除它们。

现在,您可以通过以下方式从 websocket 线程中访问 write_message:[client.write_message('#your_message') for client inconnections]

关于python - Tornado 发送有关事件的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40654193/

相关文章:

python - 用计数器替换 pd.MultiIndex 级别 2

python - 动态生成具有唯一名称的字典条目

websocket - 使用 chrome 框架而不是 SockJS

javascript - 在 Tabris.js 中使用 Websocket api 连接到 socket.io 服务器

python - 分析 Tornado/Asyncio 时哪些函数是免费的?

python - 科学数据包 : Convert one-hot encoding to encoding with integers

python - Pygame鼠标点击更新?

javascript - 如何在 Windows 7 中使用 Nodejs?

python - 如何在 Tornado 上使用卡夫卡?

python - 在 Tornado 中将 Content-Length header 从服务器写入客户端