Python flask-socketio not connecting

I’m using flask-socketio to send data between a python web server and a client web page.

Server Code :

from flask import Flask, render_template, send_from_directory
from flask_socketio import SocketIO,emit

app=Flask(__name__, static_url_path='', static_folder="static/")
socketio=SocketIO(app)

@socketio.on('connect')
def test_connect():
    print("socket connected")

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

Javascript client code :

const socket=io('http://localhost:5000');
socket.on('connect',()=>{
  console.log('connected!');
}

Now,when I run it locally on my computer,it works fine.
But when I deployed it on Glitch and ran it, It gave me few warnings as :

Serving Flask app (lazy loading)
Environment: production
WARNING: Do not use the development server in a production environment. Use a production WSGI server instead.
Debug mode: on
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Restarting with stat WebSocket transport not available. Install eventlet or gevent and gevent-websocket for improved performance.
Debugger is active!
Debugger PIN: 327-937-508

And my code wasn’t working. I was able to open index.html but the console didn’t log “socket connected”. Also, none of my other socket emits were working.

After going through a few stack overflow questions, I changed my server code to :

from flask import Flask, render_template, send_from_directory
from flask_socketio import SocketIO,emit
from gevent.pywsgi import WSGIServer


app=Flask(__name__, static_url_path='', static_folder="static/")

http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()

socketio=SocketIO(app)

@socketio.on('connect')
def test_connect():
    print("socket connected")

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

This fixed the warnings but everything still doesn’t work.

Any way to fix this?

Change io('http://localhost:5000') to just io() the code is no longer running on localhost aka your computer.

But socketio defaults to port 3000, and flask-socketio is running on 5000. How to change the ports?

try it with io() and see what happens, socketio’s port is probaly different from the server config
glitch has this thing called a reverse proxy in which traffic coming from the internet on port 80 and 443 gets rerouted to your app which in this case is on 5000.

1 Like

Okay. Changing client to io() and python server to socketio.run(app,port=3000) seems to work nicely.
Thank you.