简体   繁体   English

无法使用 Flask 连接到 SocketIO

[英]Cannot connect to SocketIO using Flask

I'm trying to create an app that uses SocketIO, I'm using Flask-socketio and using Socket.io Client Tool to test the connection of the socket.我正在尝试创建一个使用 SocketIO 的应用程序,我正在使用 Flask-socketio 并使用Socket.io 客户端工具来测试套接字的连接。 I've done it as shown in the flask-socketio's documentation but I am not able to connect the socket.我已经按照flask-socketio的文档中所示完成了它,但我无法连接套接字。 I get the following errors while connecting:连接时出现以下错误:

Client Error:客户端错误: 在此处输入图像描述

Server Side Error:服务器端错误: 在此处输入图像描述

The code:编码:

app = Flask(__name__)
CORS(app)
app.config.from_object(Config)
socketio = SocketIO(app)

jwt = JWTManager(app)
db = MongoEngine(app)
api = Api(app)


@app.route('/')
def messageReceived(methods=None):
    if methods is None:
        methods = ['GET', 'POST']
    print('message was received!!!')


# @socketio.on('connect', namespace='/test')
# def test_connect():
#     print('Client connected')
#
#
# @socketio.on('disconnect', namespace='/test')
# def test_disconnect():
#     print('Client disconnected')


@socketio.on('my event')
def handle_my_custom_event(json, methods=None):
    if methods is None:
        methods = ['GET', 'POST']
    print('received my event: ' + str(json))
    socketio.emit('my response', json, callback=messageReceived)


if __name__ == '__main__':
    app.run(debug=True, host='localhost', port=5000)
    socketio.run(app, logger=True, engineio_logger=True)

The Flask-SocketIO server enforces a same-origin policy by default. Flask-SocketIO 服务器默认执行同源策略。 You need to configure the origin from your Socket.IO test tool as an allowed origin.您需要将您的 Socket.IO 测试工具的来源配置为允许的来源。 For example:例如:

socketio = SocketIO(app, cors_allowed_origins="https://amritb.github.io")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM