我正在使用Python3构建App服务器,并且前端是通过node完成的。 js和套接字。 IO与后端连接。 后端使用Python Flask框架;同样,使用socketio和前端进行连接,但是连接失败 更改套接字版本的尝试失败。
=====================这是python服务器端代码==================== ===
from werkzeug.exceptions import HTTPException
from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO, emit, Namespace
from flask_cors import CORS
app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
class APINamespace(Namespace):
def on_test(self, data):
print(str(data))
emit('message', {'data': 'received ' + data['data'] + '!!!'})
socketio.on_namespace(APINamespace('/api'))
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', port=8000, debug=True)
======================这是HTML测试代码==================== ====
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Socket.IO Chat Example</title>
<script src="jquery-2.1.4.min.js"></script>
<script src="socket.io.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
var opts = {
'reconnection':false,
'force new connection': true,
'transports':['websocket', 'polling']
};
var socket = io.connect('http://127.0.0.1:8000/api',opts);
socket.on('message', function() {
$('#log').append('<br>connect<br>');
socket.emit('test', {'account': 'user1','name':'user1'});
});
});
</script>
</head>
<body>
<div><p id="log">这里显示信息<br></p></div>
</body>
</html>
我设想后端实际打印出来自前端的数据{'account':'user1','name':'user1'}
但是,当网页打开时,后端控制台将仅打印此消息
(3039)接受('127.0.0.1',1707)127.0.0.1--[16 / Aug / 2019 14:01:10]“ GET / socket.io /?EIO = 3&transport = websocket HTTP / 1.1” 400122 0.000404
前控制台会打印一条错误消息,说明握手失败
socket.io.js:8与'ws://127.0.0.1:8000 / socket.io /?EIO = 3&transport = websocket'的WebSocket连接失败:WebSocket握手期间出错:意外的响应代码:400