Python Flask emit() 函数不向客户端发送实时数据

我制作了一个倒数计时器,并在 for 循环中放置了 emit 函数。但是 emit 不会将我的计时器数据发送给客户端。


这是我的 python 服务器端代码:


from flask import Flask,render_template,render_template_string

from flask_socketio import SocketIO, emit


app = Flask(__name__) 

app.config['SECRET KEY'] = 'random'

socketio = SocketIO(app)


@app.route('/') 

def index():

    return render_template('index.html')


@socketio.on('test_timer')

def Timer(seconds=3600):

    def hms(seconds): # hour minute second function

        h = seconds // 3600

        m = seconds % 3600 // 60

        s = seconds % 3600 % 60

        return '{:02d}:{:02d}:{:02d}'.format(h, m, s)


    for i in range(seconds):

        emit(hms(seconds-i),broadcast=True)

        emit.sleep(1)


if __name__ == '__main__':

    socketio.run(app,debug=True)

这是我的客户端 javascript 代码:


<!DOCTYPE html>


<html>

    <body>

        <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>

        <script type="text/javascript" charset="utf-8">

            var socket = io().connect('http://127.0.0.1:5000');

            socket.on('test_timer', function(receiving_data) {

            console.log(receiving_data);

            });

        </script>

    </body>

</html>

即使我运行服务器,console.log 也不会在客户端打印任何计时器数据。


慕丝7291255
浏览 298回答 1
1回答

ITMISS

下面几行显示了 emit 函数的签名&nbsp; &nbsp;def emit(self, event, data=None, room=None, include_self=True,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;namespace=None, callback=None):在您的 Flask 应用程序中,您有一个注册test_timer事件的处理程序。在此处理程序中,您需要发出一个响应事件,后跟data而不仅仅是data。例如,@socketio.on('test_timer')def Timer(seconds=3600):&nbsp; &nbsp; def hms(seconds): # hour minute second function&nbsp; &nbsp; &nbsp; &nbsp; h = seconds // 3600&nbsp; &nbsp; &nbsp; &nbsp; m = seconds % 3600 // 60&nbsp; &nbsp; &nbsp; &nbsp; s = seconds % 3600 % 60&nbsp; &nbsp; &nbsp; &nbsp; return '{:02d}:{:02d}:{:02d}'.format(h, m, s)&nbsp; &nbsp; for i in range(seconds):&nbsp; &nbsp; &nbsp; &nbsp; emit('test_timer_reply', hms(seconds-i),broadcast=True)&nbsp; &nbsp; &nbsp; &nbsp; socketio.sleep(1)在您的客户端代码中,您还需要为 发出test_timer并注册一个侦听器test_timer_reply。var socket = io().connect('http://127.0.0.1:5000');socket.emit('test_timer')socket.on('test_timer_reply', function(receiving_data) {&nbsp; console.log(receiving_data);});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript