r/learnprogramming • • Jun 27 '24

Python aiohttp websocket disconnect

Hello

I'm connecting to a websocket server from a raspberry pi pico w , I'm using aiohttp

After 50s my client is disconnect , it's not a network issue or server issue as my javascript from my browser is still connected, checked everything, I think my loop is correct but can't find the issue,

Is it a limitation of the library ?

async def main():
    session = aiohttp.ClientSession()
    async with session.ws_connect('ws://rasp-wanexa:8001') as ws:
        print('Connected to Websocket')        
        await asyncio.Future()

if __name__ == "__main__":
    asyncio.run(main())

Thanks in advance

1 Upvotes

6 comments sorted by

View all comments

Show parent comment

1

u/Comfortable-Log9908 Jun 28 '24 edited Jun 28 '24

thanks again,

so I found my issue

I declare another function for sending some message with a while loop like this:

async def main():
  session = aiohttp.ClientSession()
  async with session.ws_connect('URI') as ws:
    print('Connected to Websocket')
    await buzzer(ws)
    async for msg in ws:
      .....


async def buzzer(ws):
    while True:
        player = ''        
        if button1.is_pressed:
            print('button1 is pressed')
            player = {'id': 'buzzer', 'data': 'player1'}
            await ws.send_json(player)
            sleep(1)
        elif button2.is_pressed:
            print('button2 is pressed')
            player = {'id': 'buzzer', 'data': 'player2'}
            await ws.send_json(player)
            sleep(1)
        else:
            continue

But I don't understand why my websocket disconnected it