Send WebSocket message from Flask view

我的未来我决定 提交于 2019-12-06 15:57:56

You can use a global socket list of all client. Traverse all list and send message to all ws instance.

Example code;

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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!