deseosuho
deseosuho

Reputation: 1038

Server wait during flask app socketIO script

I'm trying to create a time delay within a server-side script of a flask web socket app.

Ultimately, I want the server to be handling many simultaneous requests, and to be able to emit back to the client two packets with a fixed time interval between.

When I use time.sleep(x) between two flask_socketio.emit statements, the client receives the socket emit events together, after the sleep has been completed.

How can I achieve Emit X; wait Y seconds; emit Z in a python flask application?

Server-side code excerpt:

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

Client-side code excerpt:

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)
    });

Console Output

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

Desired output would be for the first ping to be received at 10:43:09 and the second at 10:43:14

Upvotes: 1

Views: 1286

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67492

You are using the time.sleep() function, which I'm guessing is blocking your server. Try using socketio.sleep() instead, which would do a cooperative sleep compatible with the async framework that you are using (eventlet, gevent).

Upvotes: 3

Related Questions