您如何将消息从 Flask 服务器 (Python) 发送到 HTML 客户端?

How do you send messages from Flask server (Python) to HTML client?

为了练习,我试图让 Flask 服务器不断地将 "Hello" 打印到 HTML 页面的控制台。我目前不知道如何进行。

目前,我的服务器代码看起来像这样

app = Flask(__name__)
 app.config['SECRET_KEY'] = 'secret!'
 socketio = SocketIO(app)

@socketio.on('message')
 def handle_message(message):
    print('Message: ' + message)
     send(message)

@socketio.on('json')
 def handle_json(json):
    send(json, json=True)

@socketio.on('my event')
  def handle_my_custom_event(json):
     emit('my response', json, broadcast=True)

def hello():
    emit('message', {'hello':"Hello"})

@app.route('/')
 def index():
    return render_template('index.html')

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

虽然我的客户端代码看起来像这样:

<head>
      <script type="text/javascript" charset="utf-8">
            var socket = io.connect('http://' + document.domain + ':' + location.port);
            socket.on('connect', function() {
                 socket.emit('connected');
            });
            socket.on('message', function(data) {
                 console.log(data);
            });
      </script>
</head>

但我在控制台日志中没有收到该页面的任何信息。如何让它打印从 Flask 服务器发送到控制台的消息?我做错了什么?

我现在明白了,它应该打印 JSON 而不是 "Hello" 字符串,这也可以。我只想从服务器在 Web 控制台上打印一些内容。

下面是一个简单示例,展示了如何连接到 SocketIO 服务器并在该连接上从服务器接收消息。

app.py

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

app = Flask(__name__)                                                           
app.config['SECRET_KEY'] = 'secret!'                                            
socketio = SocketIO(app)                                                        


@socketio.on('connect')                                                         
def connect():                                                                  
    emit('message', {'hello': "Hello"})                                         


@app.route('/')                                                                 
def index():                                                                    
    return render_template('index.html')                                        


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

templates/index.html

<head>

      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
      <script type="text/javascript" charset="utf-8">
            var socket = io.connect('http://' + document.domain + ':' + location.port);
            socket.on('connect', function() {
                 console.log('connected');
            });
            socket.on('message', function(data) {
                 console.log(data);
            });
      </script>
</head>

编辑:

要让服务器每五秒发送一次 socketio 消息,您可以使用后台线程:

app.py

from flask import Flask, render_template                                        
from flask_socketio import SocketIO, emit                                       
import time                                                                     

app = Flask(__name__)                                                           
app.config['SECRET_KEY'] = 'secret!'                                            
socketio = SocketIO(app)                                                        
thread = None                                                                   


def background_thread():                                                        
    while True:                                                                 
        socketio.emit('message', {'goodbye': "Goodbye"})                        
        time.sleep(5)                                                           


@socketio.on('connect')                                                         
def connect():                                                                  
    global thread                                                               
    if thread is None:                                                          
        thread = socketio.start_background_task(target=background_thread)       


@app.route('/')                                                                 
def index():                                                                    
    return render_template('index.html')        


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