0

I have a WebSocket endpoint in FastAPI. Each ws message changes the state of one variable in the object created when the WebSocket is accepted (inside an infinite loop). Also, I want a second endless loop that prints those variables each 0.1 sec. Two of those loops should be running inside two separate treads that was created inside a fastAPI endpoint. The problem is that await self.websocket.receive_text() doesn't work and stops connection with the 1006 code. If I just print something without websocket processing, everything works fine. I guess that the newly created thread blocks the fastapi thread, but how to do that in proper way?

class Robot:
    def __init__(self, websocket):
        self.websocket = websocket

    async def move(self, websocket):
        while True:
           direction = await self.websocket.receive_text()
           print(direction)


    async def run(self):
        mover = threading.Thread(target=asyncio.run, args=(self.move(),))
        mover.start()    

@app.websocket("/ws-slave")
    async def websocket_endpoint(websocket: WebSocket):
        await websocket.accept()
        print("slave activated")
        try:
            robot = Robot(websocket)
            await robot.run()
    
            # command = await websocket.receive_text()
            # print(command)
        except WebSocketDisconnect:
            print("Connection is closed by the server")
HASKA
  • 61
  • 1
  • 6

0 Answers0