获取访问权限向客户发送消息

获取访问权限向客户发送消息

本文介绍了带有 Tornado 的 Websockets:从“外部"获取访问权限向客户发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用 WebSockets 将数据从服务器推送到连接的客户端.由于我使用 python 来编写任何类型的逻辑,因此到目前为止我一直在研究 Tornado.下面的代码片段显示了在网络上随处可见的最基本示例:

I'm starting to get into WebSockets as way to push data from a server to connected clients. Since I use python to program any kind of logic, I looked at Tornado so far. The snippet below shows the most basic example one can find everywhere on the Web:

import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web

class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        print 'new connection'
        self.write_message("Hello World")

    def on_message(self, message):
        print 'message received %s' % message
        self.write_message('ECHO: ' + message)

    def on_close(self):
    print 'connection closed'


application = tornado.web.Application([
  (r'/ws', WSHandler),
])


if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

事实上,这按预期工作.但是,我无法理解如何将这种集成"到我的应用程序的其余部分中.在上面的例子中,WebSocket 只向客户端发送一些东西作为对客户端消息的回复.如何从外部"访问 WebSocket?例如,通知所有当前连接的客户端发生了某种事件——并且该事件不是来自客户端的任何类型的消息.理想情况下,我想在我的代码中写一些类似的东西:

As it is, this works as intended. However, I can't get my head around how can get this "integrated" into the rest of my application. In the example above, the WebSocket only sends something to the clients as a reply to a client's message. How can I access the WebSocket from the "outside"? For example, to notify all currently connected clients that some kind event has occured -- and this event is NOT any kind of message from a client. Ideally, I would like to write somewhere in my code something like:

websocket_server.send_to_all_clients("Good news everyone...")

我该怎么做?或者我是否完全误解了 WebSockets(或 Tornado)应该如何工作.谢谢!

How can I do this? Or do I have a complete misundersanding on how WebSockets (or Tornado) are supposed to work. Thanks!

推荐答案

您需要跟踪所有连接的客户端.所以:

You need to keep track of all the clients that connect. So:

clients = []

def send_to_all_clients(message):
    for client in clients:
        client.write_message(message)

class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        send_to_all_clients("new client")
        clients.append(self)

    def on_close(self):
        clients.remove(self)
        send_to_all_clients("removing client")

    def on_message(self, message):
        for client in clients:
            if client != self:
                client.write_message('ECHO: ' + message)

这篇关于带有 Tornado 的 Websockets:从“外部"获取访问权限向客户发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 11:19