python 关于Flask-Socket IO的错误:当客户端连接到服务器时,它不断抛出400个错误请求

dgsult0t  于 2023-02-28  发布在  Python
关注(0)|答案(1)|浏览(200)

我想实现前端和后端之间的WebSocket,我在网上找到了这个例子,但是当我运行代码时,它总是抛出400错误。这是flask服务器代码:

from flask import Flask, render_template
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret_key'

socketio = SocketIO()
socketio.init_app(app, cors_allowed_origins='*')

name_space = '/dcenter'

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/push')
def push_once():
    event_name = 'dcenter'
    broadcasted_data = {'data': "test message!"}
    socketio.emit(event_name, broadcasted_data, broadcast=False, namespace=name_space)
    return 'done!'

@socketio.on('connect', namespace=name_space)
def connected_msg():
    print('client connected.')

@socketio.on('disconnect', namespace=name_space)
def disconnect_msg():
    print('client disconnected.')

@socketio.on('my_event', namespace=name_space)
def mtest_message(message):
    print(message)
    emit('my_response',
         {'data': message['data'], 'count': 1})

if __name__ == '__main__':

    socketio.run(app, host='0.0.0.0', port=5000, debug=True)

这是客户端代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SocketIO Demo</title>
    <script type="text/javascript" src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
    <script type="text/javascript" src="//cdn.bootcss.com/socket.io/1.5.1/socket.io.min.js"></script>
</head>
<body>

<h2>Demo of SocketIO</h2>
<div id="t"></div>
<script>
$(document).ready(function () {
    namespace = '/dcenter';
    var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port + namespace);
    socket.on('dcenter', function (res) {
        var t = res.data;
        if (t) {
            $("#t").append(t).append('<br/>');
        }

    });
});
</script>
</body>
</html>

这是错误消息:"GET /socket.io/?EIO=3&transport=polling&t=OQIAKtK HTTP/1.1" 400
我尝试更改flak-socketio和engine-io的版本并找到另一个示例代码,但都失败了。

b4wnujal

b4wnujal1#

在你的html文件里。
socket.io.min.js的版本1.5.1太旧:

<script type="text/javascript" src="//cdn.bootcss.com/socket.io/1.5.1/socket.io.min.js"></script>

您应该使用更新的版本,如4.5.4:

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.4/socket.io.min.js" ></script>

Python主要有4个组件,它们必须相互兼容。我使用以下组件/版本:
在HTML文件中:

#version socket.io == 4.5.4
#more versions availabe here: https://cdnjs.com/libraries/socket.io

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.4/socket.io.min.js" ></script>

Package :

Flask-SocketIO == 5.3.2
python-engingeio == 4.3.4
python-socketio == 5.7.2

以下是以下版本的概述:
https://flask-socketio. readthedocs. io/en/latest/intro. html #:~:text = Flask%2D套接字IO %20与%20多种%20不同%20配置中的%20多种%20配置%20兼容。

相关问题