无法使用 Flask 连接到 SocketIO
Cannot connect to SocketIO using Flask
我正在尝试创建一个使用 SocketIO 的应用程序,我正在使用 Flask-socketio 并使用 Socket.io Client Tool 来测试套接字的连接。我已经按照 flask-socketio 的文档中所示完成了它,但我无法连接套接字。连接时出现以下错误:
客户端错误:
服务器端错误:
代码:
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)
Flask-SocketIO 服务器默认执行同源策略。您需要将 Socket.IO 测试工具的来源配置为允许的来源。例如:
socketio = SocketIO(app, cors_allowed_origins="https://amritb.github.io")
我正在尝试创建一个使用 SocketIO 的应用程序,我正在使用 Flask-socketio 并使用 Socket.io Client Tool 来测试套接字的连接。我已经按照 flask-socketio 的文档中所示完成了它,但我无法连接套接字。连接时出现以下错误:
客户端错误:
服务器端错误:
代码:
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)
Flask-SocketIO 服务器默认执行同源策略。您需要将 Socket.IO 测试工具的来源配置为允许的来源。例如:
socketio = SocketIO(app, cors_allowed_origins="https://amritb.github.io")