I try to use asyncio rather than qt.QTcpSocket as the client, but the socket can receive msgs only if the mouse is hovering the the Slicer UI

import asyncio

async def tcp_echo_client(message):
    reader, writer = await asyncio.open_connection(
        '127.0.0.1', 8888)

    print(f'Send: {message!r}')
    writer.write(message.encode())
    await writer.drain()

    data = await reader.read(100)
    print(f'Received: {data.decode()!r}')

    print('Close the connection')
    writer.close()
    await writer.wait_closed()

asyncio.run(tcp_echo_client('Hello World!'))

But this seems not be able to automatically get the messages from the server side.

loop = qt.QEventLoop()
asyncio.set_event_loop(loop)

Can I use the above to get qt eventloop to get the messages from the server automatically? Thanks!

I haven’t seen a general purpose way to use our Qt event loop with asyncio, so if you or anyone here has a good solution please post it.

The WebServer module in Slicer uses the QSocketNotifier class to add a python socket’s file number to the Qt event loop so that everything is event driven. I find this to be a good solution.

There should be a way to do something similar with asyncio such that events from Qt can be used to trigger event handling in asyncio code, but when I looked a few years ago it seemed that the core event loops in asyncio were not set up for this use case. Maybe there are good solutions by now.

1 Like

Thanks a lot! Indeed helpful! Will try QSocketNotifier.

You may consider using the WebServer module in Slicer. Commonly needed features are exposed via the slicer endpoint, it has an exec option to allow full access to the entire Slicer Python API, and you can also start a SlicerHTTPServer with your own RequestHandler to support any custom requests. So, you actually don’t need to go down to the asincio or QSocketNotifier level or deal with any communication stuff at all, just implement a simple Python class that has canHandleRequest and handleRequest methods (Slicer’s default request handler can serve as an example).

1 Like

Thank you very much for the help! That is really great! Will try with it!