question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Not reconnecting when used with FastAPI server

See original GitHub issue

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

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
cetteupcommented, Feb 5, 2021

Thank’s a lot for you work on this!

In the meantime, I just re-installed from the master branch and I can confirm that the reconnect now works as intended.

1reaction
miguelgrinbergcommented, Feb 4, 2021

@cetteup Okay, I did find something wrong in the asyncio client reconnects. Your examples apps were useful, thanks for spending the time and creating them.

With the fix applied in this repository on master the reconnection works. However, there is another related issue that I’m seeing. When the Socket.IO log in the client shows the line Waiting for write loop task to end I see a long delay of about 20 seconds before the actual reconnect attempts begin. This delay occurs with or without the fix that I have applied. Did you also see that long delay?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Cannot connect to fast api server at localhost:8000 from my ...
You need to use the command uvicorn main:app --reload --host 0.0.0.0. Your docker container is like a computer, which is independent.
Read more >
09 : FastAPI Connecting to a Database - FastapiTutorial
Our database and server are now connected to each other. In case we are using SQLite, we don't even need to create database...
Read more >
Background Tasks - FastAPI
Background Tasks¶. You can define background tasks to be run after returning a response. This is useful for operations that need to happen...
Read more >
A Deep Dive into Connecting FastAPI with SingleStore.
Variable to use to connect to the MySQL database. To make SQLAlchemy create our data models on the SingleStoreDB server, we need to...
Read more >
Building a CRUD App with FastAPI and MongoDB
Pydantic Schema's are used for validating data along with serializing (JSON -> Python) and de-serializing (Python -> JSON). It does not serve as...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found