fastapi websocket connection after some time

125 Views Asked by At
from fastapi import FastAPI, WebSocket
# import asyncio
import uvicorn

app = FastAPI()

# Dictionary to store WebSocket connections in groups
groups = {}

class ConnectionManager:
    async def connect(self, websocket: WebSocket, group: str):

        try: 
            await websocket.accept()
            
            if group not in groups:
            
                groups[group] = set()

            groups[group].add(websocket)
        except Exception as e:
            print('in connect method:', e)
            self.disconnect(websocket, group)

    def disconnect(self, websocket: WebSocket, group: str):
        
        try:
            groups[group].remove(websocket)
        
        except Exception as e:   
            print('in disconnect method:', e)
            
    async def send_to_group(self, group: str, message: str):
        try:
            if group in groups:
            
                # print(group, groups[group])
            
                for websocket in groups[group]:
                    print('send')
                    await websocket.send_bytes(message)

        except Exception as e:
            print('in send to group file:',e)
            self.disconnect(websocket, group)

manager = ConnectionManager()

@app.websocket("/ws/{group}")
async def websocket_endpoint(websocket: WebSocket, group: str):
    
    await manager.connect(websocket, group)
    
    try:
    
        while True:
    
            data = await websocket.receive_bytes()
            # Broadcast the received message to the group
            await manager.send_to_group(group, data)
    
    except Exception as e:
        print('in websocket endpoint:',e)
        manager.disconnect(websocket, group)

if __name__ == "__main__":
  
    uvicorn.run(app, host="0.0.0.0", port=8000)

this is my websocket endpoint where group are made and user can broadcast message in that group by connecting in that group.


import io, requests
from websockets.sync.client import connect

while True:

    try:

        with connect(f"ws://127.0.0.1:8000/ws/{host_name}",) as ws:
         
            try:

                while True:

                    data = 'bytes data'
                    # Send the encoded image over WebSocket
                    ws.send(data)
                    
                
            except Exception as e:
                print('first exception')
                print(e)
                # Clean up
                ws.close()

    except Exception as e:
        print('second exception')
        print(e)
        pass            

this is my client side code for sending continiusly screenshot bytes data to that group and front end side , they also connect to that group to receive that screenshot.

but problem with this code it that it stops sending message in group without any error. can anyone please explain this to me?

0

There are 0 best solutions below