[Python] Flask SocketIO not firing event

Discussão em 'Python' iniciado por Stack, Outubro 24, 2024.

  1. Stack

    Stack Membro Participativo

    I have a flask app and using SocketIO i am trying to send an “alert” to a webpage. Which webpage the alert is sent to depends on which item the alert belongs to. The problem I am having is any message the client sends to the server, has no effect within the server.

    Here is the Python console output. It receives the message fine, but then seems to do nothing with it?

    received event "test_event" from g-XoIzwtN4Lv6NThAAAB [/]
    INFO: socketio.server: received event "test_event" from g-XoIzwtN4Lv6NThAAAB [/] tZWHMirft12nVmxiAAAA: Received packet MESSAGE data 2["join_workstation", "CX"]
    INFO: engineio.server:tZWHMirftl2nVmxiAAAA: Received packet MESSAGE data
    2["join_workstation","СХ"
    received event "join_workstation" from g-XoIzwtN4Lv6NThAAAB [/]
    INFO: socketio.server:received event "join_workstation" from g-XoIzwtN4Lv6NThAAAB [/]
    tZWHMirftl2nVmxiAAAA: Received packet MESSAGE data 2["join_workstation"]


    Here is the browser console output:

    LOGListening for alarms on namespace: /
    LOGDone
    LOGConnected to server
    LOGAttempting to join


    Here is the relevant part of the web page:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.6.1/socket.io.js"></script>
    <script>
    document.addEventListener('DOMContentLoaded', (event) => {

    const alarmsDiv = document.getElementById('alarms');
    const debugDiv = document.getElementById('debug');
    const workstationId = '{{ workstation.ID }}';
    debugDiv.innerHTML += '<p>DomContentLoaded event fired</p>';
    if (typeof io !== 'undefined')
    {
    debugDiv.innerHTML += '<p>Socket.IO library loaded succesfully</p>';

    }

    const socket = io({transports: ['websocket'], upgrade:false });
    if(socket.connected == true )
    {
    console.log("Connected?")
    }
    socket.on('disconnect', function(data)
    {
    console.log("Connected to server");
    });


    socket.on('connect', () =>
    {
    console.log("Connected to server");
    console.log("Attempting to join")
    debugDiv.innerHTML += '<p>Connected to server</p>';
    socket.emit('join_workstation', workstationId)
    socket.emit("join_workstation")
    });

    socket.on('connected', () =>
    {
    console.log("Server cobfurned");
    debugDiv.innerHTML += '<p>Server confirmed connection</p>';
    });

    socket.on('joined_workstation', (data) => {
    console.log("Joined")
    debugDiv.innerHTML += '<p>Joined room</p>'
    })
    socket.on('alarm', (data) =>
    {
    console.log("Alarm received")
    debugDiv.innerHTML += '<p>Alarm from server</p>';

    alarmsDiv.innerHTML += `<p>ALARM: Headcode ${data.headcode} in Berth ${data.berth}</p>`;
    const berthDIV = document.getElementById(`berth-${data.berth}`);
    if (berthDiv)
    {
    berthDiv.querySelector('.contents').textContent = data.headcode
    }

    });
    console.log("Listening for alarms on namespace:", socket.nsp);
    socket.emit('test_event',namespace='/alarms/{wstn_id}')
    console.log("Done")




    });

    </script>


    Here is the code belonging to the webserver. I have added various logging to try and see what’s happening, but to no avail.

    from flask import Flask, render_template
    from flask_socketio import SocketIO, emit, join_room
    from Classes.Config import Configuration
    import logging

    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger(__name__)
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    socketio = SocketIO(app, cors_allowed_origins='*', logger=True, engineio_logger=True)


    @app.route('/workstation/<ws_id>')
    def workstation_page(ws_id):
    ws = Configuration.workstations.get(ws_id) # Assuming Config.berths is your berth dictionary
    if not ws:
    return "Workstation not found", 404
    berthslist = ws.berths
    return render_template('index.html', workstation=ws, berths = berthslist)

    @socketio.on('connect')
    def on_connect():
    logger.debug("Client connected")
    print(f"Conencted to client ")
    emit('connected', {'data': 'Connected'})

    @socketio.on('disconnect')
    def handle_disconnect():
    logger.debug("Client disconnected")


    @socketio.on("join_workstation", namespace = "/")
    def on_join_workstation(data):
    logger.debug(f"join workstation event")
    try:

    if isinstance(data, str):
    ws_id = data
    elif isinstance(data, dict):
    ws_id = data.get('ws_id')
    else:
    print("invalid data")
    return
    room = f'workstation_{ws_id}'
    join_room(room)
    print(f"Client joined workstation_{ws_id}")
    emit('joined_workstation', {'room': room})
    except Exception as e:
    logger.error(f"Error in handle_join {str(e)}")





    @socketio.on('test_event', namespace=f'/')
    def on_test_event(ws_id, data):
    print("Received Test Event")

    def send_alarm(headcode, berth, WS_ID, ):
    print("ALARM")
    socketio.emit('alarm', {'headcode': headcode, 'berth': berth, 'workstation':WS_ID})


    Here is the relevant part of the webpage



    Expecting Python to at least print “client connected” or “join workstation event” but neither occur. The browser console confirms it is doing that, and the Python console confirms it receives it

    Continue reading...

Compartilhe esta Página