rharder
rharder

Reputation: 348

aiohttp Websocket doesn't close when connected to some websocket servers

Using Python v3.5 or v3.6 websocket clients are not closing when connected to some websocket servers. The example code below shows the process working correctly when connected to wss://echo.websocket.org but fails to disconnect when connecting to wss:/stream.pushbullet.com.

Can anyone see what's the difference? It hardly seems like it should have anything to do with the server and how it behaves (or possibly misbehaves).

import asyncio
import aiohttp

# Code: http://pastebin.com/G5sfpQG2
# Closing the echo.websocket.org connection works as expected
# Closing the stream.pushbullet.com connection hangs

async def run():
    session = aiohttp.ClientSession()
    API_KEY = "RrFnc1xaeQXnRrr2auoGA1e8pQ8MWmMF"  # (OK to have here)
    async with session.ws_connect('wss://stream.pushbullet.com/websocket/' + API_KEY) as ws:
    # async with session.ws_connect("wss://echo.websocket.org") as ws:
        ws.send_json({"hello": "world"})

        async def _timeout():
            await asyncio.sleep(2)
            print('closing ... ', end="", flush=True)
            await ws.close()
            print('... closed. Should see "broke out of ..." messages next')

        asyncio.get_event_loop().create_task(_timeout())

        async for ws_msg in ws:
            print("ws_msg:", ws_msg)

        print("broke out of async for loop")
    print("broke out of async with")
    session.close()

loop = asyncio.get_event_loop()
loop.run_until_complete(run())
print("goodbye")

Upvotes: 2

Views: 1829

Answers (2)

nesdis
nesdis

Reputation: 1220

While the user has already answered the question, I have found the issue of servers not closing the socket, still prevalent on aiohttp 2.0 as well.

Many a times this is an issue with the server as well! After debugging it turns out some servers don't close ssl connections according to protocol. For such servers adding the following parameters while creating the connector object usually does the job.

force_close=True, enable_cleanup_closed=True

Adding this information for users who maybe still facing this issue on 2.0.

Upvotes: 1

rharder
rharder

Reputation: 348

sigh Version 1.3.0 of aiohttp fixed this. I'll assume it was a bug. I was on v1.2.0.

-Rob

Upvotes: 0

Related Questions