Python 套接字服务器在部署时不工作

Python socket server not working when deployed

我正在尝试构建一个聊天机器人,但在部署我的服务器时遇到了一些问题

该程序在本地运行,但是当我尝试在 Heroku 中部署服务器时,我一直收到“net::ERR_CONNECTION_TIMED_OUT”。我尝试了所有方法,但找不到解决方案。

客户:

<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>

服务器:

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 命令:

git push heroku master
heroku run python server.py

当我尝试连接时 Heroku 记录:

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

我的过程文件

web: python server.py

在我 运行 server.py 之后,出现一条消息说服务器正在 运行ning at 0.0.0.0:8080

但是我无法连接到服务器。

当你在 Heroku 中 运行 时,你必须将你的网络服务器放在 PORT 环境变量中指示的端口号上。你的代码总是把它放在 8080.

试试这个:

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