简体   繁体   中英

Socket.IO Emit Sending in Delay

I'v created a Flask-SocketIO python server that should log data from a socket.io JavaScript client.

Server:

from flask import Flask, render_template
from flask_socketio import SocketIO

app = Flask(__name__)
socketio = SocketIO(app)

@socketio.on('connect')
def handle_connect():
    print 'Connected'

@socketio.on('disconnect')
def handle_disconnect():
    print 'Disconnected'

@socketio.on('start')
def handle_start():
    print 'Start'

@socketio.on('log')
def handle_log(data):
    print('Log: ' + data) 

if __name__ == '__main__':
    socketio.run(app)

Client:

<script src="socket.io.js"></script>

<script>
    function sleep(ms) {
        var unixtime_ms = new Date().getTime();
        while(new Date().getTime() < unixtime_ms + ms) {}
    }

    var socket = io.connect('http://127.0.0.1:5000', {'forceNew':true });
    socket.on('connect', function()
    {
        socket.emit('start');
        socket.emit('log', '1');
        socket.emit('log', '2');
        socket.emit('log', '3'); 

        sleep(3000)
    });
</script>

Instead of seeing the server printing "Start", "Log: 1", "Log: 2" and "Log: 3" immediately.

The server only prints "Start" and after 3 seconds prints all the other messages in one shot.

This is a problem as I require realtime logging, and cannot afford receiving all the logs in one shot at the end of execution.

Any idea why this is happening and what is the correct way to implement this simple log server?

The sleep() function that you are using is really bad for JavaScript, as you aren't really sleeping but busy-waiting. That means that the CPU is engaged during those 3 seconds, so other tasks that need CPU to run get delayed.

If you need to wait 3 seconds before doing something else, I suggest you use a timer object:

window.setTimeout(function() { alert('do something!'); }, 3000);

If you sleep using a timeout you will be releasing the CPU during the wait time, and that allows the JS scheduler to give it to other tasks that need it, such as those that support the Socket.IO emits.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM