pythonflaskwebsocketsocket.ioflask-socketio

Flask-SocketIO Events Not Functioning


I'm currently developing a Flask web application with SocketIO. The basics work, but when I make a custom event (see example), the server doesn't respond to it. Can this be because I'm just using app.run() instead of socketio.run()?

Python File (snippet):

app = Flask(__name__)
socket = SocketIO(app)

@socket.on('test_event')
def handle_test_event(data):
    rec_data = data['data']
    print(rec_data)

app.run(debug=True)

Front End (snippet):

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.1/socket.io.js"></script>
<script>
    var socket = io.connect('http://' + document.domain + ':' + location.port);

    window.onload = function() {
        console.log("Called onload");
        socket.emit('test_event', {'data': 'Hello World'});
    }
</script>

My event, initiated on the client side using socket.emit(), is not triggering the corresponding event handler on the server (@socketio.on(...)). I've checked my connection and the other things, but I can't figure out why the event isn't being received and processed by the server.


Solution

  • You are creating socket = SocketIO(app) but not running this in any way. Instead, you run app. It turns out that you launched the application itself, and not the socket.

    You need to use socket.run(app) to run the application and listen for events

    https://flask-socketio.readthedocs.io/en/latest/getting_started.html#initialization