Search code examples
herokuwebsocketdeploymentsocket.iopython-socketio

Python socket server not working when deployed


I'm trying to build a chatbot, but I'm having some issues deploying my server

The program works locally, but when I try to deploy the server in Heroku, I keep receiving, "net::ERR_CONNECTION_TIMED_OUT". I tried everything but I can't find the solution for that.

Client:

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>

   <script>
      var socket = io("http://bot.herokuapp.com:8080");
      
      function appendHtml(el, str) {
          el[0].innerHTML += str;
      }
      
      document.getElementsByClassName('input')[0].addEventListener("keyup", function(event) {
          if (event.keyCode === 13) {
            event.preventDefault();
            sendMsg();
          }
      });
      
      function sendMsg() {
        var html = '<div class="message">' + document.getElementsByClassName('input')[0].value + '</div>';
        appendHtml(document.getElementsByClassName('messages'), html); 
        socket.emit("message", document.getElementsByClassName('input')[0].value);
        document.getElementsByClassName('input')[0].value = "";
      }
      
      socket.on("message", function(data) {
       var html = '<div class="message">' + data.response + '</div>';
       setTimeout(function(){ 
        appendHtml(document.getElementsByClassName('messages'), html); 
       }, 1000);
      });
   </script>

Server:

from aiohttp import web
import socketio
from chatbot.robot import getResponse

# creates a new Async Socket IO Server
sio = socketio.AsyncServer(cors_allowed_origins='*')
# Creates a new Aiohttp Web Application
app = web.Application()
# Binds our Socket.IO server to our Web App
# instance
sio.attach(app)

async def index(request):
    with open('index.html') as f:
        return web.Response(text=f.read(), content_type='text/html')

@sio.on('message')
async def print_message(sid, message):
    await sio.emit('message', {'response': getResponse(message)}, room=sid)

app.router.add_get('/', index)

if __name__ == '__main__':
    web.run_app(app)

Heroku commands:

git push heroku master
heroku run python server.py

Heroku logs when I try to connect:

at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=bot.herokuapp.com request_id=... fwd="..." dyno= connect= service= status=503 bytes= protocol=http

My procfile

web: python server.py

After I run the server.py, a message appears saying that the server is running at 0.0.0.0:8080

But I can't connect to the server.


Solution

  • When you run inside Heroku you have to put your web server on the port number indicated in the PORT environment variable. Your code always puts it in 8080.

    Try this:

    if __name__ == '__main__':
        port = int(os.environ.get('PORT', 8080))
        web.run_app(app, port=port)