Peter
Peter

Reputation: 120

Flask-socketio (server side) not receivng events

I've been playing around with flask-socketio but can't get it to work.

My project directory is set up like this:

Project
├── app
│   └── main
│   │   └── __init__.py
│   │   └── events.py
│   │   └── portal
│   │       └── __init__.py
│   │       └── routes.py
│   └── templates
│   |    └── index.html
│   └── __init__.py
└── run.py
└── __init__.py

My run.py file:

from app import create_app, socketio

app = create_app()


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

app\__init__.py file

from flask import Flask

from app.main.admin.routes import admin
from app.main.api.routes import api
from app.main.website.routes import website
from app.main.portal.routes import portal

import os

from flask_socketio import SocketIO

socketio = SocketIO()


def create_app():
    app = Flask(__name__)

    app.secret_key = os.urandom(24)

    # Initialise extensions
    socketio.init_app(app)


    with app.app_context():
        app.register_blueprint(website)
        app.register_blueprint(portal, url_prefix="/portal")
    return app

events.py:

from .. import socketio

@socketio.on('hello')
def handle_hello(data):
    print(data)

And finally alert.html:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
    <script>

        var socket = io.connect('http://' + document.domain + ':' + location.port);

        function hey() {
            socket.emit('hello', {'data': 'hello peter r'});
        }
    </script>
</head>
<body>
    <button onclick="hey()">Hello</button>
</body>

In events.py the event hello never seems to be received and nothing is printed. I'm assuming it's a problem with the way I imported the file but I don't see any problems in the code. Can someone please help?

Update: I've added a socket.on('connect') event to my alert.html (client) code and the client is connecting but the server (events.py) wont receive any thing.

Upvotes: 0

Views: 940

Answers (1)

Gijs Wobben
Gijs Wobben

Reputation: 2060

The problem is that your events.py files is never accessed by you app. It's not imported or opened in any way. Because of that the handler never get's registered.

We're missing some of your code, so I've made a minimal working example. Just put all these in the same folder:

run.py

from main import create_app, socketio

# Import the handler, you don't actually have to do anything with it, just import
import events

# Create the app
app = create_app()


if __name__ == "__main__":

    # Run the app on a specific port
    socketio.run(app, debug=True, port=5006)

main.py

import os

from flask import Flask
from flask_socketio import SocketIO

# Create the socketio app
socketio = SocketIO()


def create_app() -> Flask:

    # Create a Flask app
    app = Flask(__name__, static_folder="./")
    app.secret_key = os.urandom(24)

    # Initialise extensions
    socketio.init_app(app)

    # Register some endpoints, in this case just serve index.html
    @app.route('/')
    def index():
        return app.send_static_file('index.html')

    return app

events.py

from main import socketio

@socketio.on('hello')
def handle_hello(data):
    print(data)

index.html

<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.1/socket.io.js" integrity="sha512-AcZyhRP/tbAEsXCCGlziPun5iFvcSUpEz2jKkx0blkYKbxU81F+iq8FURwPn1sYFeksJ+sDDrI5XujsqSobWdQ==" crossorigin="anonymous"></script>
        <script>
            const socket = io.connect('http://localhost:5006/');

            // Show a message when we're connected to the server
            socket.on('connect', () => console.log('We\'re connected!'));

            function hey() {
                socket.emit('hello', {
                    'data': 'Hello Peter!'
                });
            }
        </script>
    </head>
    <body>
        <button onclick="hey()">Hello</button>
    </body>
</html>

Upvotes: 1

Related Questions