服务器在烧瓶应用程序 socketIO 脚本期间等待

Server wait during flask app socketIO script

我正在尝试在 Flask Web 套接字应用程序的服务器端脚本中创建时间延迟。

最终,我希望服务器能够处理许多并发请求,并且能够以固定的时间间隔向客户端发回两个数据包。

当我在两个 flask_socketio.emit 语句之间使用 time.sleep(x) 时,客户端会在睡眠完成后一起接收套接字发出的事件。

如何在 python flask 应用程序中实现 Emit X; wait Y seconds; emit Z

服务器端代码摘录:

from flask import Flask, request
from flask_socketio import SocketIO, join_room, emit
app = Flask(__name__)
socketio = SocketIO(app)
@socketio.on('ping')

def ping(appState):
    """send 2 pings, between a time interval"""
    room = appState["sessionID"]
    emit('serverPingResponse', {'room': room, 'msg':"Ping Received by Server"})
    time.sleep(5)
    emit('serverPingResponse', {'room': room, 'msg':"2nd time-delayed ping"})
    return

客户端代码摘录:

var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on("serverPingResponse", function(msg){
      // listen to server ping and print the message to console
      let d = new Date();
      console.log("ping received at "+d.toLocaleTimeString(), msg)
    });

控制台输出

pinging server...
ping received at 10:43:14 AM 
Object { room: "wvdhj01f3p", msg: "Ping Received by Server" }
ping received at 10:43:14 AM 
Object { room: "wvdhj01f3p", msg: "2nd time-delayed ping" }

期望的输出是在 10:43:09 收到第一个 ping,在 10:43:14

收到第二个 ping

您正在使用 time.sleep() 功能,我猜它正在阻止您的服务器。尝试使用 socketio.sleep() 代替,这将执行与您正在使用的异步框架(eventlet、gevent)兼容的合作睡眠。