[Python] Use Flask-SocketIO to send messages continuously

Discussão em 'Python' iniciado por Stack, Março 4, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to build an application to monitor files on my local computer through the browser. I have written a minimalistic example to illustrate this.

    The frontend should be able to request messages from the backend on events. In my example below, I am calling these "standard messages". They are triggered in the frontend by a button click and a fetch call, and handled in the backend by a route.

    The backend should also send messages every 5 seconds. I am calling these "continuous messages" and I am trying to send them using Flask-SocketIO. They are sent by the backend with socketio start_background_task and emit, and are received by the frontend with socket.on().

    The "standard messages" part works fine if I comment the socketio part (and replace socketio.run with app.run). But when I uncomment the socketio part to have "continuous messages", the communication fails. The backend doesn't receive the "standard messages" calls, and the frontend doesn't receive the "continuous messages".

    It looks like I am not writing the socketio part correctly. What do I need to add so that both messages type work correctly?

    Backend

    import time

    from flask import Flask
    from flask_cors import CORS
    from flask_socketio import SocketIO

    app = Flask(__name__)
    CORS(app)

    # Continuous messages ##########################################
    socketio = SocketIO(app, cors_allowed_origins="*")

    @socketio.on('connect')
    def handle_connect():
    print('Client connected')
    socketio.start_background_task(send_continuous_messages)

    def send_continuous_messages():
    while True:
    print("Backend sends a continuous message")
    socketio.emit("continuous_message", {"data": "New continuous message"})
    time.sleep(5)
    ################################################################

    @app.route("/standard-message", methods=["GET"])
    def generate_standard_message():
    print("Backend sends a standard message")
    return {"data": "New standard message"}

    if __name__ == "__main__":
    print("Starting app")
    socketio.run(app, debug=True)



    Frontend

    const myButton = document.getElementById('my-button');
    const BASE_URL = "http://localhost:5000";

    // Continuous messages #########################################
    const socket = io(BASE_URL);

    socket.on('connect', () => {
    console.log('WebSocket connected');
    });

    socket.on('disconnect', () => {
    console.log('WebSocket disconnected');
    });

    socket.on('continuous_message', (data) => {
    console.log('Frontend received a continuous message:', data);
    });
    // #############################################################

    async function receiveStandardMessage() {
    console.log('Frontend is requesting a standard message');
    const response = await fetch(`${BASE_URL}/standard-message`);
    const data = await response.json();
    console.log('Frontend received a standard message:', data);
    }

    myButton.addEventListener('click', receiveStandardMessage);



    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My app</title>
    <script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
    </head>
    <body>
    <div id="app">
    <button id="my-button">Send standard message</button>
    </div>
    <script src="app.js"></script>
    </body>
    </html>


    Server logs

    Starting app
    * Restarting with stat
    Starting app
    * Debugger is active!
    * Debugger PIN: 141-243-050
    (1244) wsgi starting up on http://127.0.0.1:5000
    (1244) accepted ('127.0.0.1', 49486)
    127.0.0.1 - - [04/Mar/2025 08:45:34] "GET /socket.io/?EIO=4&transport=polling&t=PLW7WJA HTTP/1.1" 200 335 0.000959
    Client connected
    127.0.0.1 - - [04/Mar/2025 08:45:34] "POST /socket.io/?EIO=4&transport=polling&t=PLW7WJj&sid=nPtLaSPxia-m_47UAAAA HTTP/1.1" 200 202 0.004389
    Backend sends a continuous message
    Backend sends a continuous message
    Backend sends a continuous message


    Client logs

    Frontend is requesting a standard message
    Firefox can’t establish a connection to the server at ws://localhost:5000/socket.io/?EIO=4&transport=websocket&sid=nPtLaSPxia-m_47UAAAA.
    WebSocket disconnected

    Continue reading...

Compartilhe esta Página