trio-websocket icon indicating copy to clipboard operation
trio-websocket copied to clipboard

Should `WebSocketConnection` be an asynchronous iterator?

Open mehaase opened this issue 7 years ago • 4 comments

The connection object could be an iterator that yields incoming messages, i.e. as an alternative to calling get_message().

# simple WebSocket echo
async with open_websocket(…) as websocket:
    async for message in websocket:
        await websocket.send(message)

Thoughts?

mehaase avatar Sep 17 '18 20:09 mehaase

Note: Aaugustin's Websockets has async iterable connection objects: https://websockets.readthedocs.io/en/stable/api.html#module-websockets.protocol

On Python ≥ 3.6, WebSocketCommonProtocol instances support asynchronous iteration:

async for message in websocket:
   await process(message)

The iterator yields incoming messages. It exits normally when the connection is closed with the status >code 1000 (OK) or 1001 (going away). It raises a ConnectionClosed exception when the connection is >closed with any other status code.

mehaase avatar Oct 18 '18 16:10 mehaase

Raising only on connection error sounds good

belm0 avatar Oct 18 '18 23:10 belm0

Yes I think it's nice idea, websockets impl is here, very simple ?

https://github.com/aaugustin/websockets/blob/13eff12bb4c995b50154fdc250281c92ddccaca0/src/websockets/legacy/protocol.py#L469

Also it seems aaugustin is moving his implementation to have a sans-io base, just for FYI

Ivoz avatar Oct 17 '21 18:10 Ivoz

Oh cool, I like aaugustin’s library, nice to hear that it is adopting sans io. This library here is not maintained anymore (I’ve changed jobs twice since I wrote it) so it would be great to have an async library with an active maintainer.

mehaase avatar Oct 17 '21 19:10 mehaase