1

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

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

在下面的示例中(来自 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()
4

1 回答 1

4

您可以使用所有客户端的全局套接字列表。遍历所有列表并向所有 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()
于 2017-11-28T07:33:05.657 回答