Establishing TCP connection without blocking the main thread


I’m programming a simple multiplayer online game. It’s menu has a button used for connecting to the server. The handler function of this button calls a subroutine with ConnectionManager.open_TCP_client_connection() which blocks the main thread (assuming that connection takes a while). I want the application to display a responsive dialog with button ‘Cancel’ while it’s connecting to the server. What would be the best way to use open_TCP_client_connection() without blocking the main thread? Is it possible to do so with a coroutine? Or maybe should I spawn a new thread?

Simplified code with blocking can look like:

    def connect_button_handler(self):
        show_dialog('Connecting...', 'Cancel')
        connected = connect()  # contains open_TCP_client_connection()
        if connected:
             show_dialog('Connected!', 'OK')

I could run the whole function in a separate thread, but I’m not sure if it’s a safe/elegant solution

Thank you :slight_smile:

Hi, welcome to the forum!

I think running it in a separate thread is your best bet. It looks like that particular method doesn’t currently support asynchronous use. Feel free to open a feature request on GitHub, though.

1 Like