【问题标题】:socket.io works on local network but not when deployed on a vps serversocket.io 在本地网络上工作,但在部署在 vps 服务器上时不工作
【发布时间】:2023-02-09 03:37:27
【问题描述】:

我正在为随机数生成器创建一个接口。只需在我的机器上使用脚本,它就可以完美运行。 但是当我在服务器(IONOS VPS)上托管接口时,它无法正常工作。我仍然可以访问界面并加载 html。有时它会显示一个发出的数字或 2,而当我仍在等待时,有时界面会收到另一个数字。

在我的 python 控制台中,我定期收到对 /socket.io/?EIO=4&transport=polling&t=00maxxx 的 GET 请求。

这是我的浏览器网络控制台显示的内容。 enter image description here

我想这种联系从来没有真正完全发生过。 我已经检查了 flask-socketio 与我的服务器的兼容性。

我的服务器代码如下所示:

from flask import Flask, render_template
from flask_socketio import SocketIO, emit
from flask_cors import CORS
import eventlet
import threading

eventlet.monkey_patch()

async_mode = None

app = Flask(__name__)
CORS(app)
socketio = SocketIO(app, async_mode='async_mode', logger=True)

# starting background thread
def background_thread():
    while True:
        socketio.emit('my_response',
                      {'data': 'Server generated event'})

# create html template
@app.route("/")
def index():
    return render_template('index.html', async_mode=socketio.async_mode)

@socketio.event
def my_ping():
    emit('my_pong')

<... more vent handlers etc. ...>

if __name__ == '__main__':


    PORT = json.load(open('config.json'))["PORT"]
    print("Running on localhost:"+str(PORT))

    socketio.run(app, debug=True, host='0.0.0.0', port=PORT)

客户端看起来像这样:

<!DOCTYPE HTML>
<html lang="en">
<head>
    <!--Used character set -->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Random Number Generator</title>

    <script charset="utf-8" src="{{ url_for('static', filename='js/jquery.min.js') }}">
    <script charset="utf-8" src="{{ url_for('static', filename='js/socket.io.js') }}"></script>
    <script charset="utf-8" src="{{ url_for('static', filename='js/server.js') }}" type="text/javascript"></script>

    
</head>

<body>
    More HTML here
</body>

</html>

我的 server.js 看起来像这样

var socket = io();

$(document).ready(function() {

some code 

});

// Interval function that tests message latency by sending a "ping"
    // message. The server then responds with a "pong" message and the
    // round trip time is measured.
    var ping_pong_times = [];
    var start_time;
    window.setInterval(function() {
        start_time = (new Date).getTime();
        $('#transport').text(socket.io.engine.transport.name);
        socket.emit('my_ping');
    }, 1000);

    // Handler for the "pong" message. When the pong is received, the
    // time from the ping is stored, and the average of the last 30
    // samples is average and displayed.
    socket.on('my_pong', function() {
    var latency = (new Date).getTime() - start_time;
    ping_pong_times.push(latency);
    ping_pong_times = ping_pong_times.slice(-30); // keep last 30 samples
    var sum = 0;
    for (var i = 0; i < ping_pong_times.length; i++)
        sum += ping_pong_times[i];
        $('#ping-pong').text(Math.round(10 * sum / ping_pong_times.length) / 10);
    });

任何人都知道问题是什么?

【问题讨论】:

    标签: python flask socket.io flask-socketio python-socketio


    【解决方案1】:

    您的连接可能永远不会升级到 websockets。如果是这种情况,它会保持轮询模式,每 25 秒轮询一次。 More info on the ping interval

    但是,我还看到您正在使用 eventlet 和猴子修补它,但是您将 async_mode 设置为字符串 'async_mode' 而不是您定义的值 None 更高一点。我会尝试将其设置为'eventlet',看看是否可以解决问题。 像这样:

    import eventlet
    import threading
    eventlet.monkey_patch()
    
    app = Flask(__name__)
    CORS(app)
    socketio = SocketIO(app, async_mode='eventlet', logger=True)
    

    此外,如果您使用的是开发网络服务器,则可能需要使用 Gunicorn。 Socketio deployment with Gunicorn

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-16
      • 1970-01-01
      • 2013-01-14
      • 1970-01-01
      相关资源
      最近更新 更多