问题描述
我在我的 mac 上安装了多次 Flask-socketio,仔细阅读说明并安装要求(eventlet/gevent)。虽然当我运行我的简单代码进行测试时,它要么说我没有导入模块,要么在我在浏览器中打开 index.html 之前什么都不显示,然后显示:
The client is using an unsupported version of the Socket.IO or Engine.IO protocols (further occurrences of this error will be logged with level INFO)
这是我的 app.py 代码:
from flask import Flask
from flask_socketio import SocketIO,send
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hello'
socketio = SocketIO(app,cors_allowed_origins='*')
@socketio.on('message')
def handle(msg):
print("message: "+msg)
send(msg,bradcast=True)
if __name__ == '__main__':
socketio.run(app)
这是我的 index.html 代码(如果需要):
<html>
<head>
<title>Chat Room</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
var socket = io.connect('http://127.0.0.1:5000');
socket.on('connect',function() {
socket.send('User has connected!');
});
socket.on('message',function(msg) {
$("#messages").append('<li>'+msg+'</li>');
console.log('Received message');
});
$('#sendbutton').on('click',function() {
socket.send($('#myMessage').val());
$('#myMessage').val('');
});
});
</script>
<ul id="messages"></ul>
<input type="text" id="myMessage">
<button id="sendbutton">Send</button>
</body>
</html>
感谢您的帮助
解决方法
有关版本兼容性的信息,请查看 the Flask-SocketIO docs。
您已安装 Flask-SocketIO 版本 5,因此您需要 JavaScript 客户端的版本 3,但您有 1.4.8。
在 3.0.5 版中使用此 CDN URL:https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.5/socket.io.min.js