Socket.io 大约 60 秒后遇到 400(错误请求)

Socket.io encounters 400 (Bad Request) after about 60 seconds

我正在尝试使用 flask_socketio 向客户端动态发送值。但是,大约 60 秒后,我收到 400(错误请求)。我已经插入了一个 sleep(30) 来复制我的函数,它将坐在那里。第一次发射成功,而第二次发射失败。

我的服务器端是这样的:

from flask import Flask, render_template, url_for
from flask_socketio import SocketIO, Namespace, emit

import time
import json

async_mode = None
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode, pingTimeout=900)


@socketio.on('my_submit', namespace='/myID')
def test_message(message):
    lst_link = {}
    for i in range(0, 4):
        time.sleep(30)
        lst_link[str(i)+"_ele"] = "link_" + str(i).zfill(2)
        emit( 'my_values', {'data': json.dumps(lst_link)} )

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

if __name__ == "__main__":
    socketio.run(app, debug=True, host='localhost', port=5000)

我的客户端:

<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>socketio example</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
    <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js" charset="utf-8"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js" charset="utf-8"></script>
    <script src="static/js/application.js" charset="utf-8"></script>    
  </head>
  <body>
    <div>
        <button type="button" value="Submit" id="btn_submit" class="btn btn-success">Submit</button>

        <div id='values'></div>
    </div>
  </body>
</html>

最后是我的 JavaScript 代码 (src="static/js/application.js"):

$(document).ready(function() {
    namespace = '/myID';
    var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port + namespace);

    $('#btn_submit').click(function(event) {
        socket.emit('my_submit', { some_id: 'off we go' });
        return false;
    });

    socket.on('my_values', function(msg) {
      var links = JSON.parse(msg.data)
      var keys = _.keys(links)

      var content = '<div class="list-group">'

      _.each(keys, function(row){
          content = content + '<a href="/static/output/test.txt" class="list-group-item list-group-item-action" download>' + links[row] + '</a>'
          console.log(links[row])
      })

      content = content + "</div>";

      $('#values').html(content)
    })
});

async_handlers=True 添加到 socketIO 参数列表为我解决了这个问题(...现在)

socketio = SocketIO(app, async_handlers=True, pingTimeout=900)