Skip to content
Advertisement

flask web socket not connecting

i am trying to connect websocket in flask(1.1.2) with Flask-SocketIO(5.0.1) but it give 400 error to websocket url. i`m using anaconda virtual environment.

from flask import Flask, render_template
from flask_socketio import SocketIO

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

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

@socketio.on('message')
def handle_message(data):
    print('received message: ' + data)

if __name__ == '__main__':
    socketio.run(app)

#########    index.html  #########
<html>
<head>
</head>
<body>
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>
<script type="text/javascript" charset="utf-8">
    var socket = io();
    socket.on('connect', function() {
        socket.emit('my event', {data: 'I'm connected!'});
    });
</script>
</body>
</html>

my requirements.txt is – amqp==5.0.3, bidict==0.21.2, certifi==2020.12.5,click==7.1.2, dnspython==1.16.0, eventlet==0.30.0, Flask==1.1.2, Flask-SocketIO==5.0.1, gevent==21.1.1, gevent-websocket==0.10.1, greenlet==1.0.0, importlib-metadata==3.4.0, itsdangerous==1.1.0, Jinja2==2.11.2, kombu==5.0.2, MarkupSafe==1.1.1, python-engineio==4.0.0, python-socketio==5.0.4, six==1.15.0, typing-extensions==3.7.4.3, vine==5.0.0, Werkzeug==1.0.1, zipp==3.4.0, zope.event==4.5.0, zope.interface==5.2.0

Advertisement

Answer

It’s because of version compatibility, you should either downgrade your Python-socketIo version to 3 which works with SocketIo version 1 in Js, or upgrade your Js client SocketIo version to 3 which works with Python-SocketIo 5.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement