rharder

aiohttp websocket fails to close

Feb 14th, 2017
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.00 KB | None | 0 0
  1. import asyncio
  2. import aiohttp
  3.  
  4. # Closing the echo.websocket.org connection works as expected
  5. # Closing the stream.pushbullet.com connection hangs
  6.  
  7. async def run():
  8.     session = aiohttp.ClientSession()
  9.     API_KEY = "RrFnc1xaeQXnRrr2auoGA1e8pQ8MWmMF"
  10.     # async with session.ws_connect('wss://stream.pushbullet.com/websocket/' + API_KEY) as ws:
  11.     async with session.ws_connect("wss://echo.websocket.org") as ws:
  12.         ws.send_json({"hello": "world"})
  13.  
  14.         async def _timeout():
  15.             await asyncio.sleep(2)
  16.             print('closing ... ', end="", flush=True)
  17.             await ws.close()
  18.             print('... closed. Should see "broke out of ..." messages next')
  19.  
  20.         asyncio.get_event_loop().create_task(_timeout())
  21.  
  22.         async for ws_msg in ws:
  23.             print("ws_msg:", ws_msg)
  24.  
  25.         print("broke out of async for loop")
  26.     print("broke out of async with")
  27.     session.close()
  28.  
  29. loop = asyncio.get_event_loop()
  30. loop.run_until_complete(run())
  31. print("goodbye")
Add Comment
Please, Sign In to add comment