Flask SocketIO: Error during WebSocket handshake
Answer a question
I am trying to establish a websocket communication using Flask-SocketIO, but I keep getting "Error during WebSocket handshake: Unexpected response code: 400" in my browser's console.
I am using Chromium browser on Raspbian OS.
I have eventlet installed.
Here is the code of myapp.py:
from flask import Flask, jsonify, request, render_template
from flask_socketio import SocketIO, emit
import eventlet
eventlet.monkey_patch()
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
io = SocketIO(app)
clients = []
@app.route('/')
def index():
return render_template('index2.html')
@io.on('connected')
def connected():
clients.append(request.sid)
print("client connected")
print(request.sid)
@io.on('disconnect')
def disconnect():
clients.remove(request.sid)
print("client disconnected")
print(request.sid)
if __name__ == '__main__':
io.run(app, host='localhost', port=5000)
And this is index2.html:
<html>
<br>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>
</head>
<br>
<body>
<h2>HELLO</h2>
<script>
$("document").ready(function(){
var socket = io.connect('http://localhost:5000');
socket.on('connect', function() {
socket.emit('connected');
});
});
</script>
</body>
</html>
I run the application with command
python myapp.py
When I navigate to http://localhost:5000, I can see "HELLO" on the webpage, but I do not get the "client connected" message and in the browser's console, there is the error message "Error during WebSocket handshake: Unexpected response code: 400".
Does anyone have an idea what is wrong?
Answers
The server is rejecting the connection, for some reason. What you can do is enable detailed logging in the server:
io = SocketIO(app, engineio_logger=True, logger=True)
And then each time there is a 400 error you will see some additional information about the error.
A very likely cause of these 400s is a cross-origin validation that failed. It is not the only possible cause, by the most common with web browser clients. If this is the case, you will need to add the cors_allowed_origins
option to your Socket.IO server.
更多推荐
所有评论(0)