Skip to content

Calling t.cancel() after t = asyncio.create_task(server.serve_forever()) does not work #1713

@andmis

Description

@andmis

I would expect calling .cancel() on that task to cause all existing connections to disconnect, but that does not seem to happen.

STR:

import asyncio

import websockets.asyncio.server


async def handler(c):
    print("Connected")
    try:
        async for msg in c:
            print("Received:", msg)
            await c.send("ACK")
    except asyncio.CancelledError:
        raise RuntimeError("Unexpected cancellation")
    except websockets.ConnectionClosed:
        print("Disconnected")


async def main():
    try:
        s = await websockets.asyncio.server.serve(handler, "localhost", 8765)
        t = asyncio.create_task(s.serve_forever())
        await asyncio.sleep(5)
        print("Cancelling!")
        # s.close()       # This works, but
        t.cancel()        # this does not.
        await t
    except asyncio.CancelledError:
        print("Main task cancelled")


asyncio.run(main())

Launch that server, connect a WS client within 5 seconds.

  • Expected: handler disconnects, server shuts down.
  • Observed: server hangs.
>>> websockets.version.version
'15.0.1'

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions