Flask Socket-IO 和 React socket.io-客户端,客户端不接收来自“emit”的消息

Flask Socket-IO and React socket.io-client, client doesn't receive messages from 'emit

我想从另一个线程向客户端 (React JS) 发送消息(因为在那里我开始使用来自 pika 的基本消息并且它阻止了 Flask 应用程序)。 这是我在客户端的简单代码:

const socket = io.connect('ws://127.0.0.1:5000',{transports: ['websocket'], secure: true, port: '5000'});

useEffect(()=> {
    socket.emit("echo", "echo");
}, [])

socket.on('echoresponse', (data) => {
    console.log(data);
});


socket.on('update_page', (data) => {
    console.log(data);
});

当服务器收到回显时,它会回复并且一切正常。 但是当我尝试从 send_result_in_thread() 发出时,客户端什么也没收到。 我的服务器端(缺少一些 rabbitmq 鼠兔代码)

    clients = []
    app = Flask(__name__)
    socketIo = SocketIO(app, async_mode='eventlet', cors_allowed_origins="*")
    eventlet.monkey_patch()
    app.debug = True
    app.host = 'localhost'
    app.debug = True
    app.host = 'localhost'
    
 def send_result_in_thread(cli, message):
    for client in cli:
            socketIo.emit('update_page', message, room=client)
            print('sending message "{}" to client {}'.format(message.decode("utf-8"), client))
    
@socketIo.on("echo")
def echo( message):
     emit('echoresponse', "I'm alive")
    
@socketIo.on('connect')
  def handle_connect():
      print('Client connected')
      clients.append(request.sid)
    
    
@socketIo.on('disconnect')
def handle_disconnect():
     print('Client disconnected')
     clients.remove(request.sid)
    
if __name__ == '__main__':
    consumer = consumer.Consumer()
    t = threading.Thread(target=consumer.run, name="run", args=(clients, ))
    t.daemon = True
    t.start()
    socketIo.run(app, host='0.0.0.0', port='5000',
                     debug=True)

另一个话题:

class Consumer():
    def __init__(self):
        self.clients = []
        #and some more code for rabbitmq

    def got_result(self, ch, method, properties, body):
        print("CLIENTS from thread:" + str(self.clients))
        socketIo.start_background_task(send_result_in_thread, self.clients, body)

    def run(self, clients):
        self.clients = clients
        self.channel.basic_consume(self.queue_name, self.got_result)
        self.channel.start_consuming()

我在这里发现了类似的问题,作为参考https://stackoverrun.com/ru/q/12599436 但这无助于解决问题。 Client_id 成功传递给线程,调用 send_result_in_thread 但客户端没有收到消息。我不知道为什么。 提前致谢。

终于找到问题所在了。每个线程都有自己的 socketIo 变量,所以消息不会发送到客户端。我的解决方案: 主要:

t = threading.Thread(target=consumer.run, name="run", args=(clients, socketIo))

在运行中:

self.socketIo = socketIo

在got_result中:

performer.socketIo.start_background_task(performer.send_result_in_thread, self.clients, self.socketIo, body.decode("utf-8"))