【问题标题】:Flask-socketio (server side) not receivng eventsFlask-socketio(服务器端)未接收事件
【发布时间】:2021-03-25 07:58:56
【问题描述】:

我一直在玩flask-socketio,但无法让它工作。

我的项目目录是这样设置的:

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

我的run.py 文件:

from app import create_app, socketio

app = create_app()


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

app\__init__.py文件

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)

最后是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>

events.py 中,事件 hello 似乎从未被接收到,也没有打印任何内容。我假设这是我导入文件的方式有问题,但我没有在代码中看到任何问题。有人可以帮忙吗?

更新:我在我的 alert.html(客户端)代码中添加了一个 socket.on('connect') 事件,客户端正在连接,但服务器(events.py)不会收到任何东西。

【问题讨论】:

    标签: python flask socket.io flask-socketio


    【解决方案1】:

    问题是您的应用程序永远不会访问您的events.py 文件。它不会以任何方式导入或打开。因此,处理程序永远不会被注册。

    我们缺少您的一些代码,所以我做了一个最小的工作示例。只需将所有这些放在同一个文件夹中:

    运行.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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 2020-07-11
      • 2023-03-09
      • 2013-03-10
      • 2018-10-28
      • 2018-03-23
      • 2018-02-27
      • 1970-01-01
      相关资源
      最近更新 更多