Flask 套接字 IO - socket.on 方法中的发送和 return 有什么区别

Flask socket IO - what is difference between send and return in socket.on method

我正在使用反应级别的 socketIO 从烧瓶中获取数据:

from flask import Flask
from flask_socketio import SocketIO, emit, send
from flask_cors import CORS
import datetime
    
app = Flask(__name__)
CORS(app) 
socketio = SocketIO(app, cors_allowed_origins="*") # mayby too much CORS handling...

@socketio.on('time')
def time():
    current_time = datetime.datetime.now().strftime("%H:%M:%S")
    return current_time

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

在 Flask 中它工作正常,但是如果我切换到 send(current_time) 而不是 return current_time 我在 React 中得到未定义的值,那么 return() 和 [=17= 之间有什么区别] 在这种情况下 ?

import React, { useState, useEffect } from "react";
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://127.0.0.1:5000";

    
function SubscribeToTimer() {
  const [response, setResponse] = useState(1);

  useEffect(() => {
      const socket = socketIOClient(ENDPOINT);
      
      socket.emit('time', function (data) {
          console.log('time: ', data);
          setResponse(data);
        })
  },[]);

  return (
    <div>
        <p>It's {response}</p>       
    </div>
  );
}

export default SubscribeToTimer;

Python 中 Socket.IO 端点的 return 值作为 ACK 数据包(如确认)发送回客户端。 JavaScript 客户端通过在发起一切的 emit() 的完成回调中传递值,使应用程序可以访问该值:

socket.emit('time', function(data) {
    // data is what the Python event handler returns
});

当服务器调用 send() 函数时,它会向客户端发出一个 message 事件,与客户端向服务器发出的原始事件无关。要从 send() 调用中获取数据,客户端需要为 message 事件实现事件处理程序:

socket.emit('time');
socket.on('message', function(data) {
    // data is what the Python side passes in the send() call
});