Flask-socketio: Running socket.io server and socket.io client in the same app

Created on 25 Sep 2017  路  6Comments  路  Source: miguelgrinberg/Flask-SocketIO

I want to run both socket.io server and socket.io client on the same port of my localhost.

Server without client works (I use flask socket io)

from flask_socketio import send, emit, SocketIO
app = Flask(__name__)
socketio = SocketIO(app)
if __name__ == '__main__':
    socketio.run(app)

Client separately works as well

from socketIO_client import SocketIO as client_socketio, BaseNamespace
my_client = client_socketio('localhost', 5001, Namespace)
def on_aaa_response(*args):
    print('on_aaa_response', args)
my_client.on('aaa_response', on_aaa_response)
my_client.wait()

But they are mutually blocking if I start the server first - the client does not start. If I start the client first - the server will not start. Do you maybe have an idea how to start both?

question

Most helpful comment

That works flawlessly. Thanks a lot, Miguel!!!

All 6 comments

Did you try putting the server on a background thread? If you make the socketio.run(app) call in another thread, then the main thread stays free and you should be able to use your client there.

I am sorry for not doing my homework but I did not work with threads before and Internet offers approaches that are too different. How would you recommend running the server command in a background thread?

Here is a simple way (I did not test this, wrote it from memory, so maybe it needs a bit of polishing):

from flask_socketio import send, emit, SocketIO

def run_server():
    app = Flask(__name__)
    socketio = SocketIO(app)
    socketio.run(app)

socketio.start_background_task(run_server)

# do something with the Socket.IO client here!

That works flawlessly. Thanks a lot, Miguel!!!

Hey Miguel,
I am trying to run an application using app.run(). Is there some way to simultaneously run socketio.run(app) ?
Please help me if there is some way of doing that.
Thanks,
Srushti.

@SrushtiGangireddy No, socketio.run() runs the web server in the appropriate way.

Was this page helpful?
0 / 5 - 0 ratings