使用socket.io成功发送和接收事件,但没有发生任何事情

Posted

技术标签:

【中文标题】使用socket.io成功发送和接收事件,但没有发生任何事情【英文标题】:Sending and receiving events successfully with socket.io, but nothing is happening 【发布时间】:2021-10-22 04:35:21 【问题描述】:

我正在尝试让我的 web 应用程序发送消息,但我不知道为什么它不起作用。我看不到任何错误,只是我的 event.py 函数中的操作没有发生。我正在运行一个 gunicorn 服务器,其中 eventlet 工作人员为烧瓶应用程序提供服务。

这是通过 docker 启动 gunicorn 服务器的命令:

CMD [ "gunicorn", "--reload", "-b", "0.0.0.0:5000", "--worker-class", "eventlet", "-w", "1", "app:app"]

这是 notes.html 上的相关代码:

// Imports socketio
<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">

// sets domain to talk to. (empty sets it to localhost)
const socket = io()

// send message to server on trigger from form.
socket.emit('send_new_session', new_session_form_id.value, new_session_form_number.value, new_session_form_title.value, new_session_form_synopsis.value)
console.log('send_new_session')

// console logs the message here, do I know it's getting this far. The problem seems to be that the server isn't getting the message for some reason.

events.py:

from . import db, socketio
from .classes import *
from flask_socketio import emit

@socketio.on('send_new_session')
def send_new_session(id, number, title, synopsis=None):
    print("arrived!!!!!!!!!!!")
    # more code that adds the new session the the database
    ..

我已将日志记录正确设置到标准输出,但我从未看到“到达”消息,所以我知道它永远不会到达服务器。

这是我发送消息时的服务器日志:

rest-server    | Bpt-ydbpGYLF-HGKAAAC: Sending packet OPEN data 'sid': 'Bpt-ydbpGYLF-HGKAAAC', 'upgrades': ['websocket'], 'pingTimeout': 20000, 'pingInterval': 25000
rest-server    | Bpt-ydbpGYLF-HGKAAAC: Received packet MESSAGE data 0
rest-server    | Bpt-ydbpGYLF-HGKAAAC: Sending packet MESSAGE data 0"sid":"MRAxFiGYyLB3C6MBAAAD"
rest-server    | Bpt-ydbpGYLF-HGKAAAC: Received request to upgrade to websocket
rest-server    | Bpt-ydbpGYLF-HGKAAAC: Upgrade to websocket successful
rest-server    | Bpt-ydbpGYLF-HGKAAAC: Received packet MESSAGE data 2["send_new_session","1","2","foo","bar"]
rest-server    | received event "send_new_session" from MRAxFiGYyLB3C6MBAAAD [/]
rest-server    | Bpt-ydbpGYLF-HGKAAAC: Sending packet PING data None
rest-server    | Bpt-ydbpGYLF-HGKAAAC: Received packet PONG data 

您可以在日志中看到消息实际上正在发送和接收,但由于某种原因,事件中的操作没有发生。几天来我一直在尝试我能想到的一切。任何帮助将不胜感激!


下面的所有内容可能都不相关,但如果有帮助,这就是我设置应用程序的方式:


文件设置:

/app
--app.py
--requirements.txt
--Dockerfile
--docker-compose.yml
--.flaskenv
--/project
----/static
----/templates
----__init__.py
----settings.py
----events.py
----BONapp.py
----auth.py
etc...

settings.py

import os
from flask import Flask

app = Flask(__name__)
db_password = os.environ.get('DB_PASS')

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:' + db_password + '@bonmysqldb:3306/BON'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = db_password

init.py

from flask_login import LoginManager
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from flask_socketio import SocketIO
from .settings import app

db = SQLAlchemy(app)
socketio = SocketIO(app, logger=True, engineio_logger=True)

def create_app():

    migrate = Migrate(app, db)
    from .classes import Users

    db.init_app(app)
    socketio.init_app(app)
    
    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app) 

    # provide login_manager with a unicode user ID
    @login_manager.user_loader
    def load_user(user_id):
        return Users.query.get(int(user_id))

    # blueprint for auth routes of app
    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    # blueprint for non-auth parts of app
    from .BONapp import main as main_blueprint
    app.register_blueprint(main_blueprint)

    return app

app.py

from project.__init__ import create_app

app = create_app() 

【问题讨论】:

【参考方案1】:

我在再次阅读我的问题时想通了......

它在 events.py 中我改变了:

from . import db, socketio

到:

from .__init__ import db, socketio

我不确定为什么这很重要,但它解决了它。 掌心

【讨论】:

以上是关于使用socket.io成功发送和接收事件,但没有发生任何事情的主要内容,如果未能解决你的问题,请参考以下文章

Java Socket IO不会发送到Node.js,但可以连接和接收

Socket.io 是不是保证按客户端顺序接收广播事件?

socket.io和express服务器没有从客户端接收发射

socket.io 没有发送给所有客户端

ng-websocket 和 ws:客户端发送成功但没有接收

带有django和python socket io的事件