Skip to content

Not reconnecting when used with FastAPI server #622

@cetteup

Description

@cetteup

I am trying to set up a project that a) runs a local FastAPI server in order to provide a web ui/api for settings etc and b) runs a socket.io client listening for events.

I set up both the FastAPI app and the socket.io async client globally.

app = FastAPI(title='<sometitle>')
sio = socketio.AsyncClient(logger=True, engineio_logger=True)

Then run the FastAPI app via uvicorn.

if __name__ == '__main__':
    uvicorn.run(app, host=config.LISTEN_ADDR, port=config.LISTEN_PORT)

And connect to the node.js-based socket io server as one of the startup tasks.

@app.on_event('startup')
async def startup():
    await sio.connect(config.SOCKETIO_SERVER)

Which works fine. The FastAPI server starts up and does it's thing and so does the socketio client. However, if the connection to the server is lost for some reason, the client never reconnects.

Waiting for write loop task to end
INFO:engineio.client:Waiting for write loop task to end
packet queue is empty, aborting
ERROR:engineio.client:packet queue is empty, aborting
Exiting write loop task
INFO:engineio.client:Exiting write loop task
Engine.IO connection dropped
INFO:socketio.client:Engine.IO connection dropped
Exiting read loop task
INFO:engineio.client:Exiting read loop task
Connection failed, new attempt in 0.86 seconds
INFO:socketio.client:Connection failed, new attempt in 0.86 seconds
disconnected from server

That when it stops doing anything. I read through most of the similar issues in here, but unless I misunderstood, the issue should actually be fixed.

If I instead use a more default async client script, it reconnects without any issues.

import asyncio
import socketio
import time
import logging

logging.basicConfig(level=logging.DEBUG)

loop = asyncio.get_event_loop()
sio = socketio.AsyncClient(logger=True)

async def start_server():
    await sio.connect('https://qwerty-server.herokuapp.com')
    while True:
        await asyncio.sleep(5)
        await sio.send(data={'time': time.time()})

if __name__ == '__main__':
    loop.run_until_complete(start_server())

Versions I am using:
python 3.8.7 (Windows 64-bit)
socket.io 3.1.0 (on node.js 14)
fastapi 0.63.0
python-engineio 4.0.0
python-socketio 5.0.4
websockets 8.1
aiohttp 3.7.3

Metadata

Metadata

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions