从 Flask 视图发送 WebSocket 消息

Send WebSocket message from Flask view

我正在尝试制作一个使用 WebSocket 的 Flask 应用程序。 example from Flask-sockets 有效,但我如何从常规视图发送消息?

类似于 Flask-SocketIO 如何使用 .emit().send() 方法。

在下面的示例中(来自 Flask-Sockets 示例),例如,我希望能够从 hello-view 广播消息。

from flask import Flask
from flask_sockets import Sockets


app = Flask(__name__)
sockets = Sockets(app)


@sockets.route('/echo')
def echo_socket(ws):
    while not ws.closed:
        message = ws.receive()
        ws.send(message)


@app.route('/')
def hello():
    # How can I send a WebSocket message from here?
    return 'Hello World!'


if __name__ == "__main__":
    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler
    server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler)
    server.serve_forever()

您可以使用所有客户端的全局套接字列表。遍历所有列表并向所有ws实例发送消息。

示例代码;

from flask import Flask, render_template
from flask_sockets import Sockets


app = Flask(__name__)
sockets = Sockets(app)

ws_list = []

@sockets.route('/echo')
def echo_socket(ws):
    ws_list.append(ws)
    while not ws.closed:
        message = ws.receive()
        ws.send(message)


@app.route('/')
def hello():
    # How can I send a WebSocket message from here?
    return render_template('index.html')


@app.route('/send_message_to_all_client')
def broadcast():

    for ws in ws_list:
        if not ws.closed:
            ws.send("broadcast message")
        else:
            # Remove ws if connection closed.
            ws_list.remove(ws)

    return "ok"

if __name__ == "__main__":
    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler
    server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler)
    server.serve_forever()