我开始使用 WebSockets 作为将数据从服务器推送到连接的客户端的方法。由于我使用 python 来编写任何类型的逻辑,所以到目前为止我一直在研究 Tornado。下面的代码片段显示了可以在 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?例如,通知所有当前连接的客户端某种事件已经发生——并且这个事件不是来自客户端的任何类型的消息。理想情况下,我想在我的代码中的某处编写如下内容:
websocket_server.send_to_all_clients("Good news everyone...")
我该怎么做?或者我是否完全误解了 WebSockets(或 Tornado)应该如何工作。谢谢!
最佳答案
您需要跟踪所有连接的客户端。所以:
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)
关于python - 带有 Tornado 的 Websockets : Get access from the "outside" to send messages to clients,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23562465/