Home > front end >  Flask SocketIO web app refuses to accept connections from python file
Flask SocketIO web app refuses to accept connections from python file

Time:12-26

I am trying to send some data to a Flask app using web sockets. Never done something like this so I might be doing something very wrong but so far I haven't been able to accept a single connection.

For the moment I have 2 python files, server.py and client.py.

server.py starts the flask server and the web socket, then client.py should be able to connect to it, send a message, which is printed out to the server console, then the server should echo that message back where it will be received by the client and print to the client console.

However right now I am getting a Handshake status 400 BAD REQUEST error when the client tries to connect.

Here is the code I'm using:

server.py :

from flask import Flask, render_template
from flask_socketio import SocketIO

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

@app.route('/')
def sessions():
    return "Hello World"

@socketio.on('message')
def handle_my_custom_event(mes):
    print('received my event: '   str(mes))
    socketio.emit('my response', mes)

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

client.py :

import websocket

websocket.enableTrace(True)
ws = websocket.create_connection("ws://localhost:5000")
print("Sending 'Hello, World'...")
ws.send("Hello, World")
print("Sent")
print("Receiving...")
result = ws.recv()
print("Received '%s'" % result)
ws.close()

I think there is something wrong with the server.py file but, i've been flowing the Flask-SocketIO docs and its pretty much identical to their getting started example. But then again, I also don't know enough about this so i have no real idea where the problem lies.

Any help is appreciated thank you!

CodePudding user response:

The problem is with your client. Websocket and socket.io aren't the same, socket.io protocol can use websockets under the hood but you cannot just connect with websocket client to socket.io server.

What you want to use is socket.io client.

And if you don't mind I highly encuorage you to use FastAPI instead of flask. It's much simpler, faster and have much better documentation. Here you can find complete and working example of websocket server and client with FastAPI

  • Related