Celltox
Celltox

Reputation: 147

Flask-SocketIO not receiving events on server

I'm currently learning Flask and have recently found out about Flask-SocketIO. I've learned, that the module is based on events so that the client side can communicate with the server side, so I tried doing that. But for some reason, the events I send from the client side, don't make it to the server. I've tried fixing it for a few hours but I don't understand what is wrong with my code. Thanks for helping me!

main.py

from flask import Flask, render_template
from flask_socketio import SocketIO

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'

socketio = SocketIO(app)

@app.route("/", methods=["GET", "POST"])
def home():
    return render_template("index.html")

@socketio.on('my event')
def handle_my_custom_event(json):
    print('received json: ' + str(json))

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

/templates/index.html

<!DOCTYPE html>
<html lang="en">
    <h1> Chat room</h1>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous"></script>
    <script type="text/javascript" charset="utf-8">
        var socket = io();
        socket.on('connect', function() {
            socket.emit('my event', {data: 'I\'m connected!'});  #Creating event when connected
        });
    </script>

</html>

Upvotes: 0

Views: 1223

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67479

Any time things don't go the way you think they should go, you have to look for clues left in the logs. In this case that means looking at the output of the Flask process, and the browser console.

The Flask process does not show any errors, but it does show that there was no Socket.IO connection attempted. So really this isn't a problem about events not being received, but connections don't being made.

The browser console shows this:

Uncaught SyntaxError: Private field '#Creating' must be declared in an enclosing class

You see the problem? You are using # to start a comment. That should have been a // in JavaScript.

Upvotes: 1

Related Questions