0

I have a js socket.io client that only connects to my flask socket.io when i run it locally, but it does not connect when i try through heroku. the other parts of the flask api work and run good, the only thing that does not work is socket.io connection. Their is aconsole logs "disconnected", sometimes also a error in the console of Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received, even though the connection is not requested to do something.
this is my html js socket.io client code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>socket</title>
</head>
<body>
    <h1>Socket.IO Demo</h1>
    <button onclick="send()">sdgfhk</button>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.4/socket.io.js" integrity="sha512-aMGMvNYu8Ue4G+fHa359jcPb1u+ytAF+P2SCb+PxrjCdO3n3ZTxJ30zuH39rimUggmTwmh2u7wvQsDTHESnmfQ==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.0/socket.io.min.js"></script>
    <script>
        const socket = io.connect("https://onlineauctionapi.herokuapp.com/", { transports: ['websocket'] });
        socket.on("connect_error", (err) => {
        console.log(`connect_error due to ${err.message}`);
        });


        socket.on('join', () => {
            console.log("joined")
        });

        function send(){
            socket.emit('send',{message:"hello", room:"hello"})
        }

        socket.on('connect', () => {
            console.log("connected")
        });

        socket.on('disconnect', () => {
            console.log('disconnected');
        });
    </script>
</body>
</html>

this is my flask socket.io server code:

app = Flask(__name__)
CORS(app, resources={r"/api/*":{"origins":"*"}})
socketio = SocketIO(app, cors_allowed_origins="*")

@app.route('/signin', methods=['POST'])
def signIn():
    return signin(request) 
# signin is a function that signs you in

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


if __name__ == '__main__':
    socketio.run(app, int(os.environ.get('PORT', 5000)), debug=True)

this is my Procfile:

web: gunicorn main:app

this is my requirements.txt

bidict==0.22.0
cffi==1.15.0
click==8.1.3
colorama==0.4.5
dnspython==2.2.1
eventlet==0.33.1
Flask==2.1.2
Flask-Cors==3.0.10
Flask-SocketIO==5.2.0
gevent==21.12.0
gevent-websocket==0.10.1
gitdb==4.0.9
GitPython==3.1.27
greenlet==1.1.2
gunicorn==20.1.0
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.1
pycparser==2.21
pymongo==4.1.1
python-dateutil==2.8.2
python-dotenv==0.20.0
python-engineio==4.3.2
python-socketio==5.6.0
six==1.16.0
smmap==5.0.0
Werkzeug==2.1.2
zope.event==4.5.0
zope.interface==5.4.0

I tried playing around with the versions of the socket in the flask api, but it did not help. the regular requests and the socket.io requests are on the same api, and still the regular request are working, but the socket ones are not.

these are my logs from heroku:

2022-06-28T15:41:18.631530+00:00 app[web.1]: connected
2022-06-28T15:41:49.062385+00:00 heroku[router]: at=info method=GET path="/socket.io/?EIO=4&transport=websocket" host=onlineauctionapi.herokuapp.com request_id=9a63da54-26fd-4c89-a96c-f21405cd08fe fwd="46.19.85.189" dyno=web.1 connect=0ms service=30598ms status=101 bytes=202 protocol=https
2022-06-28T15:41:49.061409+00:00 app[web.1]: [2022-06-28 15:41:49 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:40)
2022-06-28T15:41:49.061951+00:00 app[web.1]: [2022-06-28 15:41:49 +0000] [40] [INFO] Worker exiting (pid: 40)
2022-06-28T15:41:49.244258+00:00 app[web.1]: [2022-06-28 15:41:49 +0000] [42] [INFO] Booting worker with pid: 42
13
  • Self-signed server certificate? Commented Jun 19, 2022 at 18:13
  • Is this possible on the free version? Commented Jun 20, 2022 at 19:05
  • i asked whether you are using a self-signed certificate in your web server as node.js would refuse to connect to the server in this case without special setup Commented Jun 20, 2022 at 19:31
  • when it is regular api requests, it is working, also from a node.js server Commented Jun 20, 2022 at 20:24
  • I think you don’t get what I mean. When connecting to a local host, SSL encryption is handled differently (if you are connecting via SSL at all when connecting to your local machine). But when you try to connect to a remote machine, make sure the certificate is trusted or that you don’t require a trusted certificate. It’s just a guess, though Commented Jun 20, 2022 at 20:29

1 Answer 1

0

Since you have the eventlet & gevent libraries, your socketio.run(...) would have been enough for socket.io to work according to the docs:

If eventlet or gevent are available, socketio.run(app) starts a production-ready server using one of these frameworks.

However, you're deploying your app in heroku using Gunicorn as your web server, which requires additional commands to start eventlet or gevent. You have 2 options - both requiring update in your Procfile:

  1. Using eventlet
web: gunicorn --worker-class eventlet -w 1 main:app
  1. Using gevent
web: gunicorn -k gevent -w 1 main:app

You can read more about this here. Also, ensure that your socketio.run(...) does not have local settings.

Sign up to request clarification or add additional context in comments.

4 Comments

both of them disable the rest of my api from working, but on the second option you gave me, the socket sometimes works when run is with socketio.run(app, host='localhost', port=5000, debug=True) and when it is only socketio.run(app) it did not work yet for me
@YakovBader Import os in your flask app then, in your socketio.run, change the port to int(os.environ.get('PORT', 33507)). Finally, remove the host='localhost'.
by the way, the api is working, so i dont think the localhost is a problem, the only part of the api that is not working, is the socket
the socket still connects randomly and usually disconnects over and over again, and the rest of the api is not working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.