ctheadn8954
ctheadn8954

Reputation: 139

Flask-SocketIo, How to share data between python thread and socketio.start_background_task thread?

Goals:

  1. socketio.run(app) launches the server and use a while loop to emit data infinitely to multiple javascripts (clients).

  2. The data comes from another while loop, but the loop needs to start once the script runs(independent from the clients connection) for other use.

Current:

  1. For point one, I have the following code already:

    def background_thread():
        while True:
            socketio.emit('response',{'data': value},namespace='/test')
    
    @socketio.on('connect', namespace='/test')
    def test_connect():
        global thread
        with thread_lock:
            if thread is None:
                thread = socketio.start_background_task(target=background_thread)
        emit('response', {'data': 'Connected'})
    
    if __name__ == '__main__':
        socketio.run(app, debug=True, host='localhost', port=args.portNum)
    

From above, I add a thread only after the clients connect to the server. I don't know how do I achieve point 2 from this point? I am thinking having another thread, but having problems organizing the code so that socketio.start_background_task can share data infinitely with the default python thread once the clients connect to the server.

An additional question: how to allow multiple clients connect to one server?

Thanks all!

Upvotes: 3

Views: 7369

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67517

I'm not sure I understand your question, but if what you are asking is how to start a thread independently of client connections, you can just start it right before you launch the server:

if __name__ == '__main__':
    socketio.start_background_task(my_other_thread)
    socketio.run(app, debug=True, host='localhost', port=args.portNum)

If you need these two threads to be synchronized, as in, when my_other_thread has a new value to send, background_thread immediately picks it up and sends it, then you can use standard thread synchronization primitives. Maybe an Event instance is what you need in this case. See the Python threading docs in the standard library.

Regarding how to allow multiple clients to connect, there is nothing you need to do for that. The server as you have it will allow connections from multiple clients.

Upvotes: 5

Related Questions